问题
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