标签:协变和逆变之疑问
关于协变和逆变已经有很多园友谈论过了,学习时也参考过园友们的文章,非常之到位!这个问题可能对您而言很简单,若有解释,请告知,在此感谢。高手绕道!
既然是标题是协变和逆变,还是先给个公认的msdn概念吧。说完概念直接进入问题区。
1 public class Employee2 {3 4 }5 6 public class Programmer : Employee7 {8 9 }
1 interface ISalary<out T> 2 { 3 T pay(); 4 void otherpay(T t); 5 } 6 7 public class BaseSalaryCounter<T> : ISalary<T> 8 { 9 public T pay()10 {11 return default(T);12 }13 14 public void otherpay(T t)15 {16 17 }18 }
ISalary<Programmer> pro = new BaseSalaryCounter<Programmer>(); ISalary<Employee> emp = pro;
毫无疑问出现错误,如下:【注】若不明白错误原因请参考园友LoveJenny文章
1 interface ISalary<out T> 2 { 3 T pay(); 4 void otherpay<T>(T t); 5 } 6 7 public class BaseSalaryCounter<T> : ISalary<T> 8 { 9 public T pay()10 {11 return default(T);12 }13 14 public void otherpay<T>(T t)15 {16 17 }18 }
1 /*定义接口*/ 2 public interface IMyComparable<in T> 3 { 4 int Compare(T other); 5 } 6 /*Employee为基类并实现其接口*/ 7 public class Employee : IMyComparable<Employee> 8 { 9 public string Name { get; set; }10 public int Compare(Employee other)11 {12 return Name.CompareTo(other.Name);13 }14 }15 16 /*Programmer继承Employee并实现其接口*/17 public class Programmer : Employee, IMyComparable<Programmer>18 {19 20 public int Compare(Programmer other)21 {22 return Name.CompareTo(other.Name);23 }24 }25 26 /*Manager继承Employee*/27 public class Manager : Employee28 {29 30 }31 32 /*定义方法*/33 34 static void Test<T>(IMyComparable<T> t1, T t2)35 {36 37 }38 39 /*调用*/40 41 Programmer p = new Programmer() { Name = "Mike" };42 Manager m = new Manager() { Name = "Steve" };43 Test(p, m);
标签:协变和逆变之疑问
原文地址:http://hzz333.blog.51cto.com/12844012/1918810