ale*_*2k8 7 powershell casting explicit-interface
码:
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.
Run Code Online (Sandbox Code Playgroud)
错误:
方法调用失败,因为[Bar]不包含名为'Foo'的方法.
你可以做类似的事情
$bar = New-Object Bar
[IFoo].GetMethod("Foo").Invoke($bar, @())
Run Code Online (Sandbox Code Playgroud)
您从对象中获取(的反射表示) 的成员并调用重载。可惜的是,人们不得不那样做。显式实现的属性等的类似方法。IFooTypeInvoke
当然,如果该方法接受参数,它们会在@()上面代码中的逗号之后进入数组。
我为 PowerShell v2.0 写了一些东西,可以很容易地以自然的方式调用显式接口:
PS> $foo = get-interface $bar ([ifoo])
PS> $foo.Foo()
Run Code Online (Sandbox Code Playgroud)
看:
http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx(存档在这里)。
它通过生成一个动态模块来实现对接口的调用。解决方案是纯 powershell 脚本(没有讨厌的添加类型技巧)。
-Oisin
| 归档时间: |
|
| 查看次数: |
3824 次 |
| 最近记录: |