本文主要是介绍《深入理解C#》——协变性和逆变性(第五章),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、委托参数的逆变性
public Form1()
{InitializeComponent();//原始button1.Click += LogPlainEvent;button1.KeyPress += LogKeyEvent;button1.MouseClick += LogMouseEvent;//裂变性示例button2.Click += LogEvent;button2.KeyPress += LogEvent;button2.MouseClick += LogEvent;
}static void LogPlainEvent(object sender, EventArgs e)
{MessageBox.Show("LogPlain");
}
static void LogKeyEvent(object sender, KeyPressEventArgs e)
{MessageBox.Show("LogKey");
}
static void LogMouseEvent(object sender, MouseEventArgs e)
{MessageBox.Show("LogMouse");
}static void LogEvent(object sender, EventArgs e)
{MessageBox.Show("An event occurred");
}
KeyPressEventArgss和 MouseEventArgs都是从EventArgs派生而来
所以可以将LogEvent方法直接赋值给KeyPress和MouseClick委托
Click、KeyPress和MouseClick的三个委托类型定义分别是
public delegate void EventHandler(object sender, EventArgs e)
public delegate void KeyPressEventHandler(object sender, KeyPressEventArgs e)
public delegate void MouseEventHandler(object sender, MouseEventArgs e)
2、委托返回类型的协变性
//声明返回Stream的委托类型
delegate Stream StreamFactory();//声明返回MemoryStream的方法
static MemoryStream GenerateSampleDate()
{byte[] buffer = new byte[16];for (int i = 0; i < buffer.Length; i++){buffer[i] = (byte)i;}return new MemoryStream(buffer);
}//利用协变性来转换方法组
StreamFactory factory = GenerateSampleDate;//调用委托以获得Stream
//factory返回的是一个MemoryStream类型的对象
//因为具有协变性,所有可以将对象赋值给stream对象
using (Stream stream = factory())
{int data;while ((data = stream.ReadByte()) != -1){Console.WriteLine(data);}
}
这篇关于《深入理解C#》——协变性和逆变性(第五章)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!