8

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'.

alex2k8
  • 42,496
  • 57
  • 170
  • 221

3 Answers3

6

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.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
5

I wrote something for PowerShell v2.0 that makes it easy to call explicit interfaces in a natural fashion:

PS> $foo = get-interface $bar ([ifoo])
PS> $foo.Foo()

See:

http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx (archived here).

It does this by generating a dynamic module that thunks calls to the interface. The solution is in pure powershell script (no nasty add-type tricks).

-Oisin

dbc
  • 104,963
  • 20
  • 228
  • 340
x0n
  • 51,312
  • 7
  • 89
  • 111
  • Thank you, Oisin! I added an answer based on your solution here http://stackoverflow.com/questions/745956/how-can-i-dispose-system-xml-xmlwriter-in-powershell/767661#767661 – alex2k8 Apr 20 '09 at 10:16
2

Bad news: It's a bug.

https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=249840&SiteID=99

Kredns
  • 36,461
  • 52
  • 152
  • 203