泛型类协方差 [英] Generic Class Covariance

查看:239
本文介绍了泛型类协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时有可能使下面的代码在C#编译?我做编译Java中类似。

 公共接口IInterface 
{
...
}

公共类的Class1:IInterface
{

}

公共抽象类基地< T>其中T:IInterface
{

}

公共类的Class2< T> :基地< T>其中T:IInterface
{

}





公众的someMethod()
{
名单,LT;基地< IInterface>>名单=新名单,LT;基地< IInterface>>();
类2< 1级>项目=新的Class2< 1级>();
list.Add(项目);这里//编译错误
}


解决方案

没有,这不是在C#合法。 C#4及以上版本支持协方差和通用接口,当它们与引用类型构造泛型委托逆变。因此,例如,的IEnumerable< T> 是协变的,所以你可以说:

 列表<&长颈鹿GT;长颈鹿=新的List<&长颈鹿GT;(){...}; 
IEnumerable的<动物>动物长颈鹿=;



而不是

 列表与LT;动物>动物长颈鹿=; 

由于动物名单可以插进一只老虎,但长颈鹿的列表不能。



不要在C#中的协变和逆变网络搜索,你会发现很多文章就可以了。


Is it possible to make the following code compile in C#? I do compile similar in Java.

public interface IInterface
{
    ...
}

public class Class1 : IInterface
{
    ...
}

public abstract class Base<T> where T : IInterface
{
    ...
}

public class Class2<T> : Base<T> where T : IInterface
{
    ...
}

.
.
.

public SomeMethod()
{
    List<Base<IInterface>> list = new List<Base<IInterface>>();
    Class2<Class1> item = new Class2<Class1>();
    list.Add(item); // Compile error here
}

解决方案

No, that is not legal in C#. C# 4 and above support covariance and contravariance of generic interfaces and generic delegates when they are constructed with reference types. So for example, IEnumerable<T> is covariant, so you could say:

List<Giraffe> giraffes = new List<Giraffe>() { ... };
IEnumerable<Animal> animals = giraffes;

but not

List<Animal> animals = giraffes;

Because a list of animals can have a tiger inserted into it, but a list of giraffes cannot.

Do a web search on covariance and contravariance in C# and you'll find lots of articles on it.

这篇关于泛型类协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆