前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >反射方法创建委托

反射方法创建委托

作者头像
用户6362579
发布2019-09-29 16:56:19
5870
发布2019-09-29 16:56:19
举报
文章被收录于专栏:小神仙小神仙
代码语言:javascript
复制
 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 }
代码语言:javascript
复制
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);
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-10-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档