【发布时间】:2011-12-16 16:44:02
【问题描述】:
是否可以确定可用于转换MarshalByRefObject 对象的接口?
强制转换运算符如何处理MarshalByRefObject 对象?是否调用CreateObjRef方法?
谢谢, 马西莫
【问题讨论】:
是否可以确定可用于转换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
}
【讨论】:
Activator.GetObject(...) 创建的远程对象的代理,那么您应该真正知道它所公开的接口,因为它已注册为wellKnownType。或者,也许您可以尝试获取 RealProxy 并调用一些受保护的方法来获取接口。这篇文章可能对您有所帮助:http://stackoverflow.com/a/7060298/1014643