简体   繁体   English

为什么动态无法在动态构建的对象上调用方法?

[英]Why does dynamic fail to invoke methods on my dynamicly built object?

I have a type that I build with TypeBuilder to match an interface, like this:: 我有一个使用TypeBuilder构建的类型来匹配接口,例如:

interface IFoo
{
     int Property{get;}
}

My code builds the get_Property method. 我的代码构建了get_Property方法。 If I cast my built object as an IFoo, everything works. 如果将构建的对象转换为IFoo,则一切正常。 However, when I use the object as a dynamic the the code complains that my IFoo does not implement get_Property. 但是,当我将该对象用作动态对象时,代码会抱怨我的IFoo没有实现get_Property。 Why is this happening, can I not use the dynamic functionality with types built at runtime? 为什么会发生这种情况,我不能在运行时将动态功能与类型一起使用吗?

dynamic uses the public API. dynamic使用公共API。 If you are using TypeBuilder it is possible that you have just provided a method and marked it as implementing that method, in which case it is (essentially) an explicit interface implementation, and undiscoverable by dynamic . 如果您正在使用TypeBuilder有可能是你刚才所提供的方法和其标记为实施该方法,在这种情况下,它是(基本上)显式接口实现,并无法发现的dynamic To use dynamic it would probably need PropertyBuilder and a public property, with the property implementation method also marked as the interface implementation. 要使用dynamic它可能需要PropertyBuilder和一个公共属性,该属性实现方法也被标记为接口实现。

For comparison, dynamic would also fail with: 为了进行比较, dynamic也会因以下原因而失败:

class Foo : IFoo {
    int IFoo.Property { get {return 5;}}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM