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 }