反射方法创建委托

  • 2019 年 10 月 10 日
  • 笔记

 1 using System;   2 using System.Linq;   3 using System.Reflection;   4 using System.Diagnostics.Contracts;   5   6 namespace Walterlv.Demo   7 {   8     public static class InstanceMethodBuilder<T, TReturnValue>   9     {  10         /// <summary>  11         /// 调用时就像 var result = func(t)。  12         /// </summary>  13         [Pure]  14         public static Func<T, TReturnValue> CreateInstanceMethod<TInstanceType>(TInstanceType instance, MethodInfo method)  15         {  16             if (instance == null) throw new ArgumentNullException(nameof(instance));  17             if (method == null) throw new ArgumentNullException(nameof(method));  18  19             return (Func<T, TReturnValue>) method.CreateDelegate(typeof(Func<T, TReturnValue>), instance);  20         }  21  22         /// <summary>  23         /// 调用时就像 var result = func(this, t)。  24         /// </summary>  25         [Pure]  26         public static Func<TInstanceType, T, TReturnValue> CreateMethod<TInstanceType>(MethodInfo method)  27         {  28             if (method == null)  29                 throw new ArgumentNullException(nameof(method));  30  31             return (Func<TInstanceType, T, TReturnValue>) method.CreateDelegate(typeof(Func<TInstanceType, T, TReturnValue>));  32         }  33     }  34 }
1             // 调用的目标实例。  2             var instance = new StubClass();  3  4             // 使用反射找到的方法。  5             var method = typeof(StubClass).GetMethod(nameof(StubClass.Test), new[] { typeof(int) });  6             Assert.IsNotNull(method);  7  8             // 将反射找到的方法创建一个委托。  9             var func = InstanceMethodBuilder<int, int>.CreateInstanceMethod(instance, method);