如何确定可用于强制转换MarshalByRefObject的接口
本文关键字:转换 MarshalByRefObject 接口 何确定 用于 | 更新日期: 2023-09-27 18:18:00
是否有可能确定可用于强制转换MarshalByRefObject
对象的接口?
强制转换操作符如何与MarshalByRefObject
对象一起工作?它调用CreateObjRef
方法吗?
谢谢,马西莫
这是一个可以用来检索接口列表的变通方法。
定义公共接口IDescriptor
public interface IDescriptor
{
List<string> GetInterfaces();
}
定义实现接口的基类:
public class BaseMasrhalByRefObject : MasrhalByRefObject, IDescriptor
{
public BaseMasrhalByRefObject() : base() {}
public List<string> GetInterfaces()
{
List<string> types = new List<string>();
foreach(Type i in GetType().GetInterfaces())
{
types.Add(i.AssemblyQualifiedName);
}
return types;
}
}
使用BaseMasrhalByRefObject而不是MasrhalByRefObject来定义服务对象:
public class MyServiceObject : BaseMasrhalByRefObject, MyInterface1, MyInterface2, ...
{
// Add logic method
}
在AppDomain A中创建MyServiceObject的引用对象。在AppDomain B中获取远程对象的代理。代理可以强制转换为IDescriptor:
public List<Type> GetInterfaces(MasrhalByRefObject proxy)
{
List<Type> types = new List<Type>();
IDescriptor des = proxy as IDescriptor;
if (des != null)
{
foreach(string t in des.GetInterfaces()) // this is a remote call
{
types.Add(Type.GetType(t);
}
}
return types;
}
MarshalByRefObject是一个类,所以只有一个接口,你不能确定是否所有实现它的类都派生自MarshalByRefObject。然而,如果你有一个对象的实例,你可以很容易地检查使用这个表达式:
if (obj1 is MarshalByRefObject)
{
// do your thing
}