C#委托的协变性和逆变性

2021-06-11 18:05

阅读:447

标签:返回   委托   button   memory   new   int   and   console   值类型   

逆变性

只要函数参数与委托兼容,就能创建委托实例。

 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 }  

 

C#委托的协变性和逆变性

标签:返回   委托   button   memory   new   int   and   console   值类型   

原文地址:https://www.cnblogs.com/love-me-love-my-code/p/10556095.html


评论


亲,登录后才可以留言!