Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 泛型类协方差_C#_Covariance - Fatal编程技术网

C# 泛型类协方差

C# 泛型类协方差,c#,covariance,C#,Covariance,可以用C语言编译以下代码吗?我用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

可以用C语言编译以下代码吗?我用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
}
公共接口接口
{
...
}
公共类1:接口
{
...
}
公共抽象类基,其中T:i接口
{
...
}
公共类Class2:T:I接口所在的基
{
...
}
.
.
.
公共方法()
{
列表=新列表();
Class2项=新的Class2();
list.Add(item);//此处编译错误
}

您不能像这样使用泛型。列表类型是IInterface,但您尝试将Class1类型添加到列表中。它应如下所示

        List<Base<Class1>> list = new List<Base<Class1>>();
        Class2<Class1> item = new Class2<Class1>();
        list.Add(item); 
List List=新列表();
Class2项=新的Class2();
列表。添加(项目);
不,这在C#中是不合法的。当泛型接口和泛型委托使用引用类型构造时,C#4及更高版本支持它们的协变和逆变。例如,
IEnumerable
是协变的,所以你可以说:

List<Giraffe> giraffes = new List<Giraffe>() { ... };
IEnumerable<Animal> animals = giraffes;
List giraffes=newlist(){…};
i可数动物=长颈鹿;
但不是

List<Animal> animals = giraffes;
列出动物=长颈鹿;
因为动物列表可以插入老虎,但长颈鹿列表不能


在网上搜索C#中的协变和逆变,你会发现很多关于它的文章。

看起来.NET Framework 4.0支持通用接口和委托中的协变。因此,我碰巧通过添加一个通用接口来编译代码

public interface IInterface
{
    ...
}

public class Class1 : IInterface
{
    ...
}

public interface IBase<out T> where T: IInterface
{
    // Need to add out keyword for covariance.
}

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

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

.
.
.

public SomeMethod()
{
    List<IBase<IInterface>> list = new List<IBase<IInterface>>();
    Class2<Class1> item = new Class2<Class1>();
    list.Add(item); // No compile time error here.
}
公共接口接口
{
...
}
公共类1:接口
{
...
}
公共接口IBase,其中T:i接口
{
//需要为协方差添加关键字。
}
公共类基:IBase,其中T:i接口
{
...
}
公共类Class2:T:I接口所在的基
{
...
}
.
.
.
公共方法()
{
列表=新列表();
Class2项=新的Class2();
list.Add(item);//此处没有编译时错误。
}

列表只是一个示例。考虑这一点:公共空洞SOMeMeod(){AdioTealMeod(new Cult2());}从以下链接中读取的公共空AnotherMethod(Base Obji){…}:只有接口和委托可以是协变的。看来我得另找解决办法了。无论如何谢谢。可能是重复的