在使用 .Net 4.0 运行时框架 RealProxy 类构造一个透明代理时,如果目标接口为泛型类型,或者继承一个泛型接口时,再通过 new Func 的方式调用泛型接口上的方法即会出现 System._Canon 类的问题。
在使用 .Net 4.0 运行时框架 RealProxy 类构造一个透明代理时,如果目标接口为泛型类型,或者继承一个泛型接口时,再通过 new Func 的方式调用泛型接口上的方法即会出现 System._Canon 类的问题。
很奇怪的一个问题,找了一个多小时了,已经追到 Com 函数调用了,仍然没找到原因,初步诊断为 .Net 框架的一个 Bug 。
代码如下:
using System;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace TestRealProxy
{
internal class Program
{
private static void Main(string[] args)
{
var service = new MyRealProxy().GetTransparentProxy() as IInterface;
// 正确的结果
var right = service.GetById(4);
// 错误的结果
Func<int, MyClass> func = service.GetById;
var error = func(3);
}
}
public interface IInterface<T> where T : class
{
T GetById(int id);
}
public interface IInterface : IInterface<MyClass>
{
}
public class MyClass
{
public int Id { get; set; }
}
public class MyRealProxy : RealProxy
{
public MyRealProxy()
: base(typeof(IInterface))
{
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage methodCall = (IMethodCallMessage)msg;
IMethodReturnMessage methodReturn = null;
object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[];
methodCall.Args.CopyTo(copiedArgs, 0);
try
{
object returnValue = new MyClass { Id = (int)methodCall.Args[0] };
methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall);
}
catch (Exception ex)
{
methodReturn = new ReturnMessage(ex, methodCall);
}
return methodReturn;
}
}
}
谁能解决这个问题?