c# - 无法转换 System.Runtime.Remoting.ObjectHandle

标签 c# c#-4.0

在我的代码中,我有一个接口(interface) - 假设它称为 InterfaceName,它的实现称为 InterfaceImpl。现在,当我动态尝试使用以下代码获取 InterfaceImpl 时:

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

出现以下错误

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

对可能出现的问题有什么建议吗?

最佳答案

If you read the documentation about the method you are calling , 它返回

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

查看ObjectHandle 的文档,您只需调用Unwrap()为了获得您要创建的类型的实例。

所以,我猜你真正的问题是......为什么?

此方法旨在在另一个 AppDomain 中调用,句柄返回调用 AppDomain,实例的代理在此处“展开”。

什么?这还不能解释为什么?

只有两种类型可以跨越 AppDomain 障碍。可序列化的类型(创建副本)和扩展类型 MarshalByRefObject (其中代理被创建和传递)。 ObjectHandle 扩展 MarshalByRefObject,因此可以跨越 AppDomain 障碍,而它们所表示的类型可能不会扩展 MBRO 可序列化。此方法可确保您无论如何都可以获得该类型的实例。

因此,如果您只是尝试实例化一个类型,您可能需要查看 CreateInstance 的不同重载。或者只是打开结果。

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

关于c# - 无法转换 System.Runtime.Remoting.ObjectHandle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13366352/

相关文章:

c# - WPF .NET Core 中的 gRPC 错误

C#:使用 Silverlight FJCore 库以 12 位精度解码 JPEG 图像?

css - 如何在IE中使用nth child

google-maps - 谷歌地图 API 是否提供建筑物的高程详细信息?

java - 在 Android 中读取和显示大格式文本文档

c# - 构建器模式实现 C# vs. JAVA

entity-framework - EF - 为什么不包括对属性的工作

c# - 主窗体上的状态消息

c# - 如何在更新面板 Asp.net C# 中保持滚动位置?

c# - 是否使用静态类