透明代理和泛型介面之間一個莫名其妙的問題

來源:互聯網
上載者:User

標籤:style   blog   color   io   使用   ar   div   問題   sp   

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

 

誰能解決這個問題?

透明代理和泛型介面之間一個莫名其妙的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.