Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

casting - How can I call explicitly implemented interface method from PowerShell?

Code:

add-type @"
    public interface IFoo
    {
        void Foo();
    }

    public class Bar : IFoo
    {
        void IFoo.Foo()
        {
        }
    }
"@ -Language Csharp

$bar = New-Object Bar
($bar -as [IFoo]).Foo() # ERROR.

Error:

Method invocation failed because [Bar] doesn't contain a method named 'Foo'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do something like

$bar = New-Object Bar
[IFoo].GetMethod("Foo").Invoke($bar, @())

You get (the reflection representaion of) the member of IFoo from the Type object and call an Invoke overload. Too bad one has to do it that way, though. Similar approach for explicitly implemented properties etc.

If the method takes arguments, they go in the array @() after the comma in the code above, of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...