C# 之委托
一:委托定义
委托也是一个类,委托派生为System.MulticastDelegate,而System.MulticastDelegate
又继承System.Delegate,如果你知道这个也就明白委托其实是一个特殊的类
语法 delegate关键字 返回类型 委托名(数据类型 参数名)
比如
无返回值定义 delegate void Mydelegate(int i);
有返回值定义 delegate int Mydelegate(int i,string arg);
二:委托调用
delegate void Mydelegate(int i); delegate string DoWork(int i, string arg); static void Main(string[] args) { Mydelegate myDelegate = new Mydelegate(ConsoleNumber); DoWork doWork = SayHello; myDelegate(1); Console.WriteLine(doWork(12, "xiaoming")); Console.ReadKey(); } static void ConsoleNumber(int i) { Console.WriteLine(i); } static string SayHello(int i, string arg) { return string.Concat(i, arg); }
三 :匿名委托
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { public class Program { delegate void Mydelegate(int i); delegate string DoWork(int i, string arg); static void Main(string[] args) { Mydelegate mydelegate = i => { Console.WriteLine(i); }; DoWork doWork = (i, s) => { return string.Concat(i, s); }; mydelegate(1); Console.WriteLine(doWork(2, "xiao,mig")); Console.ReadKey(); } static void ConsoleNumber(int i) { Console.WriteLine(i); } static string SayHello(int i, string arg) { return string.Concat(i, arg); } } }
四:委托链
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { public class Program { delegate void Mydelegate(int i); static void Main(string[] args) { Mydelegate mydelegate = ConsoleNumber; mydelegate += ConsoleNumber2; mydelegate(2); Console.ReadKey(); } static void ConsoleNumber(int i) { Console.WriteLine(i); } static void ConsoleNumber2(int i) { Console.WriteLine(i); } } }
五:Action,Func
Action 相当于定义只有参数没有返回值委托。
Func 相当于顶一个又有参数,又有返回值委托。
Action<int, string, bool> action = (i, s, b) => { Console.WriteLine(string.Concat(i, s, b)); }; Func<int, int, string, bool> func = (i1, i2, s) => { if (string.Equals(string.Concat(i1, i2), s, StringComparison.CurrentCultureIgnoreCase)) return true; else return false; }; Console.WriteLine(func(1, 2, "12"));
委托相当于匿名对象
1:var s=new{Name="xiaoming"},
Action<string> action = sf =>
{
Console.WriteLine("dfs");
};
2:
Func<string, bool> func = (ss) =>
{
if (string.IsNullOrEmpty(ss))
return true;
else
return false;
};

浙公网安备 33010602011771号