透明代理和泛型接口之间一个莫名其妙的问题

在使用 .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;
        }
    }
}

 

谁能解决这个问题?

转载于:https://www.cnblogs.com/lenic/p/3967108.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值