1

我想创建一个执行以下操作的方法:

  1. 将任意实例作为参数
  2. 生成一个包装器实例,以与传递的实例相同的方式提供所有属性和方法
  3. 用不同的实现覆盖一个方法
  4. 返回生成的实例

这与 ORM 创建的代理对象非常相似。它们通常不返回真实的模型类,而是行为相同的代理对象,除了延迟加载等。

那里有合适的东西吗?(我看到了 CodeDom,但也看到了我需要为方法实现发出的操作码......)

4

1 回答 1

1

感谢您提供所有提示和链接。Castle Project 的 DynamicProxy ( http://www.castleproject.org/projects/dynamicproxy/ ) 为我完成了这项工作。

只需覆盖单个方法(在本例中为 GetHashCode())的代理生成器就可以轻松完成:

/// <summary>
/// A class that is capable to wrap arbitrary objects and "override" method GetHashCode()
/// This is suitable for object that need to be passed to any WPF UI classes using them in
/// a hashed list, set of other collection using hash codes.
/// </summary>
public class CustomProxyFactory
{
    /// <summary>
    /// Interceptor class that stores a static hash code, "overrides" the
    /// method GetHashCode() and returns this static hash code instead of the real one
    /// </summary>
    public class HashCodeInterceptor : IInterceptor
    {
        private readonly int frozenHashCode;

        public HashCodeInterceptor( int frozenHashCode )
        {
            this.frozenHashCode = frozenHashCode;
        }

        public void Intercept( IInvocation invocation )
        {
            if (invocation.Method.Name.Equals( "GetHashCode" ) == true)
            {
                invocation.ReturnValue = this.frozenHashCode;
            }
            else
            {
                invocation.Proceed();
            }
        }
    }

    /// <summary>
    /// Factory method
    /// </summary>
    /// <param name="instance">Instance to be wrapped by a proxy</param>
    /// <returns></returns>
    public static T Create<T>( T instance ) where T : class
    {
        try
        {
            IInterceptor hashCodeInterceptor = new HashCodeInterceptor( instance.GetHashCode() );
            IInterceptor[] interceptors = new IInterceptor[] {hashCodeInterceptor};

            ProxyGenerator proxyGenerator = new ProxyGenerator();
            T proxy = proxyGenerator.CreateClassProxyWithTarget( instance, interceptors );

            return proxy;
        }
        catch (Exception ex)
        {
            Console.WriteLine( typeof(CustomProxyFactory).Name + ": Exception during proxy generation: " + ex );
            return default(T);
        }
    }
}
于 2014-06-12T13:54:14.727 回答