Hutch
Hutch

Reputation: 196

Invoking static method dynamically in powershell

I would like to invoke a static method from an object based on the class of that object. For example, assume that you have the following class structure with static methods.


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.

In this snippet above, I would like $result to contain the string "Sub1X". Any hints are appreciated.

Upvotes: 1

Views: 163

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

Same as any other static member - use the :: static member operator:

$someSubClass = [Sub1]::new()
$result = $someSubClass::getX()

Upvotes: 1

Related Questions