在使用 .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;
}
}
}
誰能解決這個問題?