Unable to cast System.Runtime.Remoting.ObjectHandle

筅森魡賤 提交于 2020-02-15 07:15:20

问题


In my code I have an interface - lets say its called InterfaceName and its implementation called InterfaceImpl. Now when I dynamically try to obtain the InterfaceImpl using the following code:

object obj = Activator.CreateInstance("ProjectName","ProjectName.Folder.InterfaceImpl");
InterfaceName in = (InterfaceName)obj; //Error pops up here

I get the following error

Unable to cast object of type 'System.Runtime.Remoting.ObjectHandle' to type 'ProjectName.Folder.InterfaceName'.

Any suggestions on what might be going wrong ?


回答1:


If you read the documentation about the method you are calling, it returns

A handle that must be unwrapped to access the newly created instance.

Looking at the documentation of ObjectHandle, you simply call Unwrap() in order to get the instance of the type you are trying to create.

So, I guess your real issue is... Why?

This method is designed to be called in another AppDomain, and the handle returned back to the calling AppDomain, where the proxy to the instance is "unwrapped".

What? That doesn't explain why?

Only two types can cross an AppDomain barrier. Types that are serializable (of which copies are created), and types that extend MarshalByRefObject (of which proxies are created and passed). ObjectHandle extends MarshalByRefObject, and so can cross that AppDomain barrier, whereas the type which they are representing may not extend MBRO or be serializable. This method ensures you can get that type instance across the barrier, no matter what.

So, if you are just trying to instantiate a type, you might want to look at a different overload of CreateInstance. Or just unwrap the result.

var obj = Activator.CreateInstance("A","A.B.C") as ObjectHandle;
InterfaceName in = (InterfaceName)obj.Unwrap(); 


来源:https://stackoverflow.com/questions/13366352/unable-to-cast-system-runtime-remoting-objecthandle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!