利用反射获得委托和事件以及创建委托实例和添加事件处理程序
最近一些都在看关于反射的内容,然后在网上大多数都是通过反射获得类型中方法,属性、字段这样的文章, 但是对于如何获得委托类型怎么去实现的却没有, 所以写下这边篇文章来让自己以后很好的复习以及想了解的朋友做参考。
一、 利用反射获得委托类型并创建委托实例
using System; using System.Reflection; namespace ConsoleApplication1 { public class Test { public delegate void delegateTest(string s); public void method1(string s) { Console.WriteLine("Create Delegate Instance: " + s); } } class Program { static void Main(string[] args) { Test test = new Test(); Type t = Type.GetType("ConsoleApplication1.Test"); // 因为委托类型编译后是作为类的嵌套类型的,所以这里通过GetNestedType(String s)的方法来获得委托类型。 Type nestType = t.GetNestedType("delegateTest"); MethodInfo method =test.GetType().GetMethod("method1", BindingFlags.Public | BindingFlags.Static|BindingFlags.Instance); if (method != null) { // 创建委托实例 Delegate method1 = Delegate.CreateDelegate(nestType, test, method); //动态调用委托实例 method1.DynamicInvoke("Hello"); } Console.Read(); } } }
二、 利用反射获得事件类型和绑定事件处理程序
using System; using System.Reflection; namespace ConsoleApplication2 { public class Test { public event EventHandler TestEvent; public void Triggle() { if (TestEvent != null) { TestEvent(this, null); } } } class Program { static void Main(string[] args) { Test testT=new Test(); EventInfo eventinfo = typeof(Test).GetEvent("TestEvent"); if (eventinfo != null) { // 为事件动态绑定处理程序 eventinfo.AddEventHandler(testT, new EventHandler(triggleEvent)); testT.Triggle(); } Console.Read(); } public static void triggleEvent(object sender, EventArgs e) { Console.WriteLine("Event has been Triggled"); } } }
希望这些使大家对放射有个更好的理解。
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能 打赏我一杯咖啡【物质支持】,也可以点击右下角的【店长推荐】按钮【精神支持】,因为这两种支持都是我继续写作,分享的最大动力


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构