C# - 动态关键字和接口实现
我假设这是不可能的,但在进一步挖掘之前,有没有办法做这样的事情:
public void ProcessInterface(ISomeInterface obj) {}
//...
dynamic myDyn = GetDynamic<ISomeInterface>()
ProcessInterface(myDyn);
我看到了 post 争论它,但听起来它没有包含在内。
一些上下文:通过 COM 公开的 .Net 程序集 -> Silverlight 应用程序使用接口实现类。通过接口引用对象会很好。真没想到,原来的目的是这样的……
I'm assuming this isn't possible but before digging further is there a way to do something like this:
public void ProcessInterface(ISomeInterface obj) {}
//...
dynamic myDyn = GetDynamic<ISomeInterface>()
ProcessInterface(myDyn);
I've seen a post arguing for it but it sounds like it wasn't included.
A little context: .Net assembly exposed through COM -> Silverlight app consuming interface-implementing classes. Would be nice to refer to the objects by interface. I really don't expect that this was what was intended...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,
dynamic
不会使类型假装实现接口(即使它通过dynamic
拥有所有方法)。将其传递给ProcessInterface
本质上会消除动态
。动态
取决于调用代码,就像实现对象一样。更多,甚至。然而,您可以创建一个使用鸭子类型的接口包装器:
No,
dynamic
won't make a type pretend to implement an interface (even if it has, viadynamic
, all the methods). Passing it toProcessInterface
essentially takes away thedynamic
.dynamic
depends on the calling code just as much as the implementing object. More, even.You could however make an interface wrapper that uses duck typing:
我想我不明白你的意思。如果您知道要处理的确切接口,为什么需要使用
dynamic
?I don't think I understand your point. If you know the exact interface you're be dealing with, why do you need to use
dynamic
?您可以使用开源Impromptu-Interface 来执行此操作。这是一种创建接口包装器并使用 DLR 的自动化方法。
Impromptu.ActLike(myDyn)
You can use the opensource Impromptu-Interface to do this. It's an automated way to make a interface wrapper and uses the DLR.
Impromptu.ActLike<ISomeInterface>(myDyn)