在powershell中动态调用静态方法
Invoking static method dynamically in powershell
我想根据对象的 class 从对象调用静态方法。例如,假设您有以下带有静态方法的 class 结构。
Class Super {
static [string] getX() {
return "X"
}
}
Class Sub1 : Super {
static [string] getX() {
return "Sub1X"
}
}
Class Sub2 : Super {
static [string] getX() {
return "Sub2X"
}
}
$someSubclass = [Sub1]::new()
#I would like to invoke getX() from this instances classes static method.
$result = $someSubclass.GetType().getX() #This (of course) does not work.
在上面的这个片段中,我希望 $result 包含字符串 "Sub1X"。
任何提示表示赞赏。
与任何其他静态成员相同 - 使用 ::
static member operator:
$someSubClass = [Sub1]::new()
$result = $someSubClass::getX()
我想根据对象的 class 从对象调用静态方法。例如,假设您有以下带有静态方法的 class 结构。
Class Super {
static [string] getX() {
return "X"
}
}
Class Sub1 : Super {
static [string] getX() {
return "Sub1X"
}
}
Class Sub2 : Super {
static [string] getX() {
return "Sub2X"
}
}
$someSubclass = [Sub1]::new()
#I would like to invoke getX() from this instances classes static method.
$result = $someSubclass.GetType().getX() #This (of course) does not work.
在上面的这个片段中,我希望 $result 包含字符串 "Sub1X"。 任何提示表示赞赏。
与任何其他静态成员相同 - 使用 ::
static member operator:
$someSubClass = [Sub1]::new()
$result = $someSubClass::getX()