我假设这是不可能的,但在进一步挖掘之前有没有办法做这样的事情:
public void ProcessInterface(ISomeInterface obj) {}
//...
dynamic myDyn = GetDynamic<ISomeInterface>()
ProcessInterface(myDyn);
我见过 post争论它,但听起来它不包括在内。
一点上下文:.Net 程序集通过 COM 公开 -> Silverlight 应用程序使用接口(interface)实现类。通过接口(interface)引用对象会很好。我真的不希望这是预期的......
最佳答案
不,dynamic
不会让类型假装实现接口(interface)(即使它通过dynamic
拥有所有方法)。将它传递给 ProcessInterface
本质上会带走 dynamic
。
dynamic
与实现对象一样依赖于调用 代码。更多,甚至。
不过,您可以制作一个使用鸭子类型的接口(interface)包装器:
class Foo : IBar {
readonly dynamic duck;
public Foo(dynamic duck) { this.duck = duck; }
void IBar.SomeMethod(int arg) {
duck.SomeMethod(arg);
}
string IBar.SomeOtherMethod() {
return duck.SomeOtherMethod();
}
}
interface IBar {
void SomeMethod(int arg);
string SomeOtherMethod();
}
关于C# - 动态关键字和接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2770487/