C#创建静态与实例方法和开放与关闭方法的委托

    技术2025-04-29  29

    public delegate void D1(C c, string s); public delegate void D2(string s); public delegate void D3(); // A sample class with an instance method and a static method. public class C { private int id; public C(int id) { this.id = id; } public void M1(string s) { Console.WriteLine(“Instance method M1 on C: id = {0}, s = {1}”, this.id, s); } public static void M2(string s) { Console.WriteLine(“Static method M2 on C: s = {0}”, s); } }

    public class Example { public static void Main() { C c1 = new C(42); MethodInfo mi1 = typeof©.GetMethod(“M1”, BindingFlags.Public | BindingFlags.Instance); MethodInfo mi2 = typeof©.GetMethod(“M2”, BindingFlags.Public | BindingFlags.Static); D1 d1; D2 d2; D3 d3; Console.WriteLine("/nAn instance method closed over C."); // 关闭实例方法委托需要调用时委托与方法有完全一致的参数类型 Delegate test = Delegate.CreateDelegate(typeof(D2), c1, mi1, false);// 使用委托类型D2调用实例方法M1.已经传递了实例c1 // 因为false指出了throwOnBindFailure 的值,当绑定失败(比如,mi1不是类型C的方法)时,test为null if (test != null) { d2 = (D2)test; // 每次调用都使用相同的类型C的实例c1 d2(“Hello, World!”); d2(“Hi, Mom!”); } Console.WriteLine("/nAn open instance method."); // 开放实例方法委托比关闭实例方法多了一个参数,它在开始时带入,代表实例方法的隐藏实例,使用委托类型D1调用实例方法M1. d1 = (D1)Delegate.CreateDelegate(typeof(D1), null, mi1);// 每次委托调用都会传递一个类型C的实例 d1(c1, “Hello, World!”); d1(new C(5280), “Hi, Mom!”); Console.WriteLine("/nAn open static method."); // 开放静态方法委托需要调用时委托与方法有完全一致的参数类型 d2 = (D2)Delegate.CreateDelegate(typeof(D2), null, mi2);// 使用委托类型D2调用静态方法M2 // 没有实例被传递,因为是静态方法! d2(“Hello, World!”); d2(“Hi, Mom!”); Console.WriteLine("/nA static method closed over the first argument (String)."); // 关闭静态方法必须省掉了方法的第一个参数,一个字符串作为第一个参数已经预先被传递,委托已经与该字符串绑定到了一起 d3 = (D3)Delegate.CreateDelegate(typeof(D3), “Hello, World!”, mi2);// 使用委托类型D3调用静态方法M2 // 每次调用委托都使用相同的字符串 d3(); } } 结果; /* This code example produces the following output:

    An instance method closed over C.Instance method M1 on C: id = 42, s = Hello, World!Instance method M1 on C: id = 42, s = Hi, Mom!An open instance method. Instance method M1 on C: id = 42, s = Hello, World!Instance method M1 on C: id = 5280, s = Hi, Mom!An open static method. Static method M2 on C: s = Hello, World!Static method M2 on C: s = Hi, Mom!A static method closed over the first argument (String).Static method M2 on C: s = Hello, World! */ 几种不同委托的异同 ———————————————————————————————— | 名称 | 使用实例 | 调用时委托与参数一致性 ———————————————————————————————— 1 |关闭实例方法委托 | 同一个 | 一致 ———————————————————————————————— 2 |开放实例方法委托 | 调用时带入 | 多一个实例作为第一个参数 ———————————————————————————————— 3 | 开放静态方法委托 | 不使用 | 一致 ———————————————————————————————— 4 | 关闭静态方法委托 | 不使用 | 少了已经预先指定的参数 ————————————————————————————————
    Processed: 0.015, SQL: 10