码迷,mamicode.com
首页 > 其他好文 > 详细

反射方法创建委托

时间:2018-10-22 10:23:38      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:open   namespace   adb   cts   play   sse   使用   nbsp   方法   

技术分享图片
 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 }
View Code
技术分享图片
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);
View Code

 

反射方法创建委托

标签:open   namespace   adb   cts   play   sse   使用   nbsp   方法   

原文地址:https://www.cnblogs.com/missile/p/9828336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!