//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.33440 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ //委托类型, 为一个对象的方法建立一个委托实例. //通过这个委托实例调用该对象的方法. //其实就是把对象方法的执行: "()"动作给抽离了. using System; namespace _004_委托 { public class Program { private delegate string GetToString ();//定义一个委托类型, 为的是指向Object.toString()方法. static void Main (string[] args) { int x = 36; /*string s = x.ToString ();//toString方法来把数据转换成字符串 Console.WriteLine (s);*/ //使用委托类型,创建实例. GetToString gts = new GetToString (x.ToString); //gts绑定了x.ToString方法. string s = gts ();//通过委托实例gts调用x中的ToString方法. // 第二种方法, 直接把函数地址赋值给委托类型的变量. GetToString gts2 = x.ToString; string s2 = gts2.Invoke (); // 通过Invoke方法调用gts2引用的方法. Console.WriteLine (s); Method method; method = Method1; method.Invoke (); method = Method2; method.Invoke (); //委托类型作为方法参数调用 PrintString methodPrint; methodPrint = Method1; PrintStr (methodPrint); methodPrint = Method2; PrintStr (methodPrint); } //把委托类型作为方法的参数 private delegate void PrintString (); static void PrintStr (PrintString print) { print ();// 间接地调用了委托类型 } private delegate void Method (); private static void Method1 () { Console.WriteLine ("Method1"); } private static void Method2 () { Console.WriteLine ("Method2"); } public Program () { } } }
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.33440 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; namespace Solution5 { public class Program { static void PrintString () { Console.WriteLine ("Hello,world."); } static void PrintInt (int i) { Console.WriteLine ("i 等于" + i); } public Program () { /*Action a = PrintString;// 委托类型a指向一个没有参数没有返回值的方法Method1*/ Action<int> b = PrintInt; } static void Main () { } } }
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.33440 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; namespace Solution6 { public class Program { static void PrintString () { Console.WriteLine ("Hello,world."); } static void PrintInt (int x, int y) { Console.WriteLine (x + y); } public Program () { } static void Main () { int[,] table = new int[10, 20]; Action a = PrintString; a (); Action<int,int> a1 = PrintInt; a1 (32, 12); } } }