这个问题几乎纯粹是为了学习目的。使用的环境是 Unity 3D 引擎。
我一直在 C# 中使用 RealProxy 和 MarhalByRefObject 类来装饰我的一个类。具体来说,我使用下面的构造函数创建了一个通用代理类。我正在装饰的类也有一个 SerializableAttribute,同时继承自 MarshalByRefObject。
public DynamicProxy(T decorated) : base(typeof(T))
{
}
获取装饰对象,最简单的代码(不带装饰)如下
ClassA toDecorate = new ClassA();
DynamicProxy proxy = new DynamicProxy<ClassA>(toDecorate);
Debug.Log(proxy.GetTransparentProxy() as ClassA);
Debug.Log((ClassA)proxy.GetTransparentProxy());
这就是奇怪的地方。我通过反射检查了类型,它确实和我要装饰的对象是同一类型。然而,令人困惑的部分是,当我正常转换(ClassA)时,我得到一个对装饰对象的引用,而当我使用 as 运算符时,返回一个空引用。
我在测试 Unity v. 2019.1.8f1 的构建时发现了这种行为。我使用的脚本运行时版本和 API 都是 .NET 4.x 等效版本。
如果有人遇到过类似的问题,我很想听听他们的情况,因为不应该发生铸造和操作员行为不同的情况,这可能会导致大量时间和精力的损失。我并不是真的在寻求解决方案,而是寻求可能比我有更好想法或遇到类似问题的人的意见。
注意:如果我只是这样做,则不会发生此行为
ClassA t = new ClassA();
object o = t;
Debug.Log(o as ClassA);
Debug.Log((ClassA)o);
编辑:经过进一步调查,我注意到 as 操作员基本上是这样做的
E is T ? (T)(E) : (T)null
发生的事情是 is 运算符返回 false。
在此处提供重现问题所需的所有代码。
public class HelloThere: MarshalByRefObject
{
public void DoStuff()
{
//Do some stuff here
Debug.Log("Doing some stuff");
}
}
public class Proxy<T> : System.Runtime.Remoting.Proxies.RealProxy
{
private T _decorated;
public Proxy(T decorated): base(typeof(T))
{
_decorated = decorated;
}
public override IMessage Invoke(IMessage msg)
{
//Do Stuff Before Function
//Call Function
var methodCall = msg as IMethodCallMessage;
var methodInfo = methodCall.MethodBase as System.Reflection.MethodInfo;
try
{
var result = methodInfo.Invoke(_decorated, methodCall.InArgs);
return new ReturnMessage(
result, null, 0, methodCall.LogicalCallContext, methodCall);
//Do Stuff After function
}
catch (Exception e)
{
return new ReturnMessage(e, methodCall);
}
}
}
此外,检查每个“铸造”返回的代码:
Proxy<HelloThere> proxy = new Proxy<HelloThere>(new HelloThere());
Debug.Log(proxy.GetTransparentProxy() as HelloThere);
Debug.Log((HelloThere)proxy.GetTransparentProxy());