【问题标题】:How can I call explicitly implemented interface method from PowerShell?如何从 PowerShell 调用显式实现的接口方法?
【发布时间】:2010-10-19 06:17:59
【问题描述】:

代码:

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.

错误:

方法调用失败,因为 [Bar] 不包含名为“Foo”的方法。

【问题讨论】:

    标签: powershell casting explicit-interface


    【解决方案1】:

    你可以这样做

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

    您从Type 对象获得IFoo 的成员(反射 表示)并调用Invoke overload。太糟糕了,但必须这样做。 显式实现的属性等的类似方法。

    如果该方法接受参数,它们当然会放在上面代码中逗号后面的数组@()中。

    【讨论】:

      【解决方案2】:

      我为 PowerShell v2.0 写了一些东西,可以很容易地以自然的方式调用显式接口:

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

      见:

      http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx(存档here)。

      它通过生成一个动态模块来实现对接口的调用。解决方案是纯 powershell 脚本(没有讨厌的 add-type 技巧)。

      -奥辛

      【讨论】:

      【解决方案3】:

      【讨论】:

      猜你喜欢
      • 2011-08-23
      • 2011-03-21
      • 1970-01-01
      • 2011-04-19
      • 2012-09-14
      • 2013-08-16
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多