views:

392

answers:

2

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

+2  A: 

Bad news: It's a bug.

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

Lucas McCoy
I have Microsoft Live account, but still can't open the link: Page Not Found. :-(
alex2k8
It opened on mine but only in IE 8, Firefox and google chrome didn't work.
Lucas McCoy
I tried IE7, Fx, Opera - no luck. Probably you can paste some citate here (if some thing usefull).
alex2k8
I tried to go back in and now it won't let me in (maybe there servers are down).
Lucas McCoy
More info: http://www.vistax64.com/powershell/169391-access-interfaces-members-net-object.html
JasonMArcher
Thank you, Jason!
alex2k8
+2  A: 

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

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

x0n
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