generics类协方差
是否可以在C#中编译以下代码? 我在Java中编译类似。
public interface IInterface { ... } public class Class1 : IInterface { ... } public abstract class Base where T : IInterface { ... } public class Class2 : Base where T : IInterface { ... } . . . public SomeMethod() { List<Base> list = new List<Base>(); Class2 item = new Class2(); list.Add(item); // Compile error here }
不,这在C#中是不合法的。 C#4及更高版本支持通用接口和通用委托在使用引用类型构造时的协方差和逆变。 所以例如, IEnumerable
是协变的,所以你可以说:
List giraffes = new List () { ... }; IEnumerable animals = giraffes;
但不是
List animals = giraffes;
因为动物名单中可以插入一只老虎,但长颈鹿的名单却不能。
在C#中进行协方差和逆变的网络搜索,你会发现很多关于它的文章。
看起来.NET Framework 4.0支持通用接口和委托中的协方差。 所以,我碰巧通过添加通用接口来编译代码。
public interface IInterface { ... } public class Class1 : IInterface { ... } public interface IBase where T: IInterface { // Need to add out keyword for covariance. } public class Base : IBase where T : IInterface { ... } public class Class2 : Base where T : IInterface { ... } . . . public SomeMethod() { List> list = new List>(); Class2 item = new Class2 (); list.Add(item); // No compile time error here. }
你不能使用像这样的generics.list类型是IInterface但你尝试将List1类型添加到list.it应该如下..
List > list = new List>(); Class2 item = new Class2 (); list.Add(item);