如何确定可用于转换MarshalByRefObject的接口?

时间:2011-12-16 16:44:02

标签: c# remoting

是否可以确定可用于转换MarshalByRefObject对象的接口?

强制转换操作符如何与MarshalByRefObject个对象一起使用?它是否调用CreateObjRef方法?

谢谢, 马西莫

2 个答案:

答案 0 :(得分:0)

MarshalByRefObject是一个只有一个接口的类,你无法确定实现它的所有类是否都来自MarshalByRefObject。但是,如果您有一个对象实例,则可以使用以下表达式轻松检查:

if (obj1 is MarshalByRefObject)
{
    // do your thing
}

答案 1 :(得分:0)

这是一种可用于检索接口列表的解决方法。

定义公共接口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中创建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;
}