利用反射获得委托和事件以及创建委托实例和添加事件处理程序

最近一些都在看关于反射的内容,然后在网上大多数都是通过反射获得类型中方法,属性、字段这样的文章, 但是对于如何获得委托类型怎么去实现的却没有, 所以写下这边篇文章来让自己以后很好的复习以及想了解的朋友做参考。

一、 利用反射获得委托类型并创建委托实例

复制代码
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");
        }
    }
}
复制代码


希望这些使大家对放射有个更好的理解。

 

posted @   Learning hard  阅读(1798)  评论(3编辑  收藏  举报
编辑推荐:
· .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语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示