Unable to cast System.Runtime.Remoting.ObjectHandle

后端 未结 1 1365
温柔的废话
温柔的废话 2021-01-17 22:46

In my code I have an interface - lets say its called InterfaceName and its implementation called InterfaceImpl. Now when I dynamically try to obtai

1条回答
  •  無奈伤痛
    2021-01-17 23:10

    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(); 
    

    0 讨论(0)
提交回复
热议问题