I have use the type dynamic, a new type in .NET 4.0.

I want to use a dynamic type because I want to use some types that in advance I don't know what type is, but I know that all this possible type has some common methods.

In my case, I am using self tracking entities in entity framework 4.0, and I know that all the entities has the methods markedXXX (to set the state of the entity).

Through the dynamic object that I created, I can access and set the properties of one of this entities, but when I try to execute the MarkedAsXXX method I get an exception that says that the object has not definied the method.

I would like to know how to access to this methods. Is it possible?

Because I have a function that can access to the original values and set this values to the current one, but I need to set the entity as Unchenged.

Thanks.

有帮助吗?

解决方案

I want to use a dynamic type because I want to use some types that in advance I don't know what type is, but I know that all this possible type has some common methods.

That suggests you should create an interface with those common methods, and make all the relevant types implement the interface.

Through the dynamic object that I created, I can access and set the properties of one of this entities, but when I try to execute the MarkedAsXXX method I get an exception that says that the object has not defined the method.

It's possible that this is due to explicit interface implementation. If the types have those methods declared as public methods in the normal way, it should be fine.

If you really want to use dynamic typing with these types, is there some base interface which declares the MarkedAsXXX methods, which you could cast the objects to before calling those methods? (I'm not familiar with the entity framework, so I don't know the details of those methods.)

Basically, I would try to avoid dynamic typing unless you really need it, partly because of edge cases like this - but if explicit interface implementation is the cause, then casting to that interface should be fine.

其他提示

If you define an interface to the dynamically generated classes you can call the methods without the hassle of reflection calling.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top