逆变性
只要函数参数与委托兼容,就能创建委托实例。
1 Button button = new Button(); 2 //public delegate void EventHandler(object sender, EventArgs e); 3 button.Click += LogPlainEvent; 4 //public delegate void KeyPressEventHandler(object sender, KeyPressEventArgs e); 5 button.KeyPress += LogPlainEvent; 6 //public delegate void MouseEventHandler(object sender, MouseEventArgs e); 7 button.MouseClick += LogPlainEvent; 8 9 public void LogPlainEvent(object sender, EventArgs e) 10 { 11 }
协变性
只要返回值类型与委托兼容,就能创建委托实例
1 public delegate Stream StreamFactory(); 2 3 public MemoryStream GenerateData() 4 { 5 return new MemoryStream(); 6 } 7 8 StreamFactory factory = GenerateData; 9 using (Stream stream = factory()) 10 { 11 int data; 12 while((data = stream.ReadByte()) != -1) 13 { 14 Console.WriteLine(data); 15 } 16 }
原文地址:https://www.cnblogs.com/love-me-love-my-code/p/10556095.html
时间: 2024-10-13 15:05:58