委托、事务
委托(普通、多播)delegate OutParm delegateName(InParm1,InParm2,......)
类似于函数指针 Delegate int Mydelegate(int a,int b)
用处:回调函数、 传递表达式 (lambda表达式:实质为泛型委托)
内置泛型委托
Aciton<int,int> 最多支持16个参数
Func<int,int,int> 最多支持16个参数,最后一个为返回参数
//定义实现Where方法 public delegate bool WhereRuler(object obj); public static class ListExpandMethod { public static void NewWhere(this List<object> list, WhereRuler rule) { List<object> newlist = new List<object>(); foreach (var item in list) { if (rule(item)) { newlist.Add(item); } } list.RemoveAll(c=>true); list.AddRange(newlist); } } //调用 List<object> list=new List<object>() { "dai","wei","daiweikuan","wdwdw"}; list.NewWhere(c => c.ToString() == "dai");
事件 event delegateName eventName
事件是一种特殊委托类型的实例,一般作为类成员,主要作用是当类的内部成员发生改变时,能通知类外部的订阅者
和委托的区别是,限定了委托了在类外部的访问权限,只能订阅,无法进行初始化
1 /// <summary> 2 /// 规则类 3 /// </summary> 4 public class RuleClass 5 { 6 private Func<List<int>, int> rule; 7 8 public Func<List<int>, int> Rule 9 { 10 get { return rule; } 11 set { rule = value; if(RuleChange!=null)RuleChange.Invoke(); } 12 } 13 14 public event Action RuleChange; 15 16 public void GetMax(List<int> ints) 17 { 18 if (Rule != null) 19 { 20 Console.WriteLine($"Max Is {Rule(ints)}"); 21 } 22 else { Console.Write("Rule no set"); } 23 24 } 25 } 26 27 /// <summary> 28 /// 接收事件通知类 29 /// </summary> 30 public class NoticeClass 31 { 32 public void NoticeRuleChange() 33 { 34 Console.WriteLine("Rule Is Changed"); 35 } 36 } 37 38 39 40 //调用 41 List<int> ints=new List<int>() { 2,3,45,334,2,0}; 42 NoticeClass noticeClass= new NoticeClass(); 43 RuleClass ruleClass = new RuleClass(); 44 ruleClass.RuleChange += noticeClass.NoticeRuleChange; //订阅规则改变事件 45 ruleClass.SetRule((list) => { return list[0]; }); //规则发生改变 46 Console.WriteLine(ruleClass.GetMax(ints));
喜欢 C#、SQL、Web