c# - 动态代理集合接口(interface)

标签 c# proxy adapter dynamicobject

我偶尔有理由编写集合类适配器,即为实现 IList<T> 的类创建一个适配器代理它的方法,添加一些额外的功能。 IList接口(interface)有很多方法/属性,我想知道直通代理方法是否可以动态实现?我看了一下 DynamicObject ,但只能找到几个代理 DTO 类的简单示例,即代理一个只有属性的类。

IList<T>的代理可能吗?

例如

public class ListProxy : IList<T>
{
  private IList<T> _adaptee;

  public ListProxy(IList<T> adaptee)
  {
    _adaptee = adaptee
  }

  // dynamically implement straight-through IList methods / properties
}

最佳答案

是这样的吗?

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;

class Program
{
    static void Main(string[] args)
    {
        IList<string> listProxy = MyProxyGenerator.Create<IList<string>>(new ListProxy<string>(new List<string>() { "aa","bb" }));
        bool b1 = listProxy.Contains("aa");
        bool b2 = listProxy.Contains("cc");
        int count = listProxy.Count;
        string s = listProxy[1];
    }

    public class ListProxy<T>
    {
        private IList<T> _adaptee;

        //Only method needed by proxy generator
        object Adaptee
        {
            get { return _adaptee; }
        }

        public ListProxy(IList<T> adaptee)
        {
            _adaptee = adaptee;
        }
    }

    class MyProxyGenerator : RealProxy
    {
        Type _Type;
        object _Instance;

        public static T Create<T>(object instance)
        {
            return (T)new MyProxyGenerator(typeof(T),instance).GetTransparentProxy();
        }

        MyProxyGenerator(Type type,object instance) : base(type)
        {
            _Type = type;
            _Instance = instance.GetType().InvokeMember("get_Adaptee", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, instance, null);
        }

        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg);
            string method = (string)msg.Properties["__MethodName"];
            object[] args = (object[])msg.Properties["__Args"];

            object retObj = _Instance.GetType().InvokeMember(method, BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,null,_Instance,args);
            return new ReturnMessage(retObj,methodMessage.Args,methodMessage.ArgCount,methodMessage.LogicalCallContext,methodMessage);
        }
    }


}

关于c# - 动态代理集合接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7658023/

相关文章:

python - 如何使用Python中的socks模块下载网页?

c# - 如何实现接受匿名类型的 C# 扩展方法

http - Sonatype 联系 : unable to use http proxy after update from 2. 2 到 2.10.0-02

c# - 如何获得本地 Visual Studio 构建完成的通知?

javascript - 如何使用 webpack-dev-server 代理代理到 ssl 端点

java - Android 适配器的 getView() 不调用 Activity

android - 自定义 ListView 适配器,奇怪的 ImageView 行为

android - 调用 setAdapter 后 ArrayList 值消失

c# - Microsoft Graph 订阅扩展错误 - 删除/更新

c# - asp.net中如何删除cookies