如何在DynamicObject中处理泛型方法调用?

时间:2011-08-05 09:19:08

标签: c# reflection dynamic .net-4.0

我正在尝试构建一个能够处理泛型方法调用的DynamicObject,但似乎所需的API - 尽管存在于RC versions of 4.0 Framework中 - 已在RTM中标记为内部(即, CSharpInvokeMemberBinder现在是内部的)。这个代码是否可以在4.0 RTM中使用?

public class TransparentObject<T> : DynamicObject {
    private readonly T target;

    public TransparentObject(T target) {
        this.target = target;
    }

    public override bool TryInvokeMember(
      InvokeMemberBinder binder, object[] args, out object result) {
        var csBinder = binder as CSharpInvokeMemberBinder;
        var method = typeof(T).GetMethod(binder.Name, BindingFlags.Public
          | BindingFlags.NonPublic | BindingFlags.Instance);
        if (method == null)
            throw new MissingMemberException(string.Format(
              "Method '{0}' not found for type '{1}'", binder.Name, typeof(T)));
        if (csBinder.TypeArguments.Count > 0)
            method = method.MakeGenericMethod(csBinder.TypeArguments.ToArray());
        result = method.Invoke(target, args);
        return true;
    }
}

(代码取自http://bugsquash.blogspot.com/2009/05/testing-private-methods-with-c-40.html

我知道我可以在这里使用反射来获取泛型类型参数,但我正在寻找一个更好的解决方案 - 如果有的话。

1 个答案:

答案 0 :(得分:0)

我猜的最快的等价物:

    private static readonly Func<InvokeMemberBinder, IList<Type>> GetTypeArguments;

    static TransparentObject()
    {
        var type = typeof(RuntimeBinderException).Assembly.GetTypes().Where(x => x.FullName == "Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder").Single();
        var dynamicMethod = new DynamicMethod("@", typeof(IList<Type>), new[] { typeof(InvokeMemberBinder) }, true);
        var il = dynamicMethod.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Castclass, type);
        il.Emit(OpCodes.Call, type.GetProperty("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder.TypeArguments", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true));
        il.Emit(OpCodes.Ret);
        GetTypeArguments = (Func<InvokeMemberBinder, IList<Type>>)dynamicMethod.CreateDelegate(typeof(Func<InvokeMemberBinder, IList<Type>>));
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        var method = typeof(T).GetMethod(binder.Name, BindingFlags.Public| BindingFlags.NonPublic | BindingFlags.Instance);
        if (method == null) throw new MissingMemberException(string.Format("Method '{0}' not found for type '{1}'", binder.Name, typeof(T)));
        var typeArguments = GetTypeArguments(binder);
        if (typeArguments.Count > 0) method = method.MakeGenericMethod(typeArguments.ToArray());
        result = method.Invoke(target, args);
        return true;
    }