5.3.3 C#1和C#2之间的一处重大改变
delegate void SampleDelegate(string x); public class SinPpet { public void CandidateAction(string x) { Console.WriteLine("Snippet.CandidateAction"); } } public class Derived : SinPpet { public void CandidateAction(object o) { Console.WriteLine("Derived.CandidateAction"); } } class Program { static void Main(string[] args) { Derived x = new Derived(); SampleDelegate factory = new SampleDelegate(x.CandidateAction); factory("test"); } }
C#2的这种心的灵活性会使本来有效的C#1代码在C#2编译时产生不同的结果。假设一个派生类重载了某个基类中声明的方法,我们打算使用方法数组转换创建一个委托的实例。由于C#2中的协变性和逆变性,一个以前只能和基类方法匹配的转换,现在也和派生类方法相匹配。在这种情况下,编译器会将选择派生类的方法。