Generics .NET4泛型问题
我的班级结构如下:Generics .NET4泛型问题,generics,c#-4.0,covariance,Generics,C# 4.0,Covariance,我的班级结构如下: public class A : AInterface { } public interface AInterface { } public class B<T> : BInterface<T> where T : AInterface { public T Element { get; set; } } public interface BInterface<T> where T : AInterface { T E
public class A : AInterface { }
public interface AInterface { }
public class B<T> : BInterface<T> where T : AInterface
{
public T Element { get; set; }
}
public interface BInterface<T> where T : AInterface
{
T Element { get; set; }
}
public class Y : B<A> { }
public class Z<T> where T : BInterface<AInterface> {}
public class Test
{
public Test()
{
Z<Y> z = new Z<Y>();
}
}
公共类A:AInterface{}
公共接口AInterface{}
公共B类:B接口,其中T:A接口
{
公共T元素{get;set;}
}
公共接口b接口,其中T:AInterface
{
T元素{get;set;}
}
公共类Y:B{}
公共类Z,其中T:BInterface{}
公开课考试
{
公开考试()
{
Z=新的Z();
}
}
这为我提供了C#4.0中的以下编译资源。
类型“Test.Y”不能用作泛型类型或方法“Test.Z”中的类型参数“T”。没有从“Test.Y”到“Test.BInterface”的隐式引用转换
我认为泛型中的协方差应该使这项工作正常?任何帮助都将不胜感激。我认为您遗漏了关键字。尝试将其添加到以下行:
public interface BInterface<out T> where T : AInterface { }
public class Z<out T> where T : BInterface<AInterface> {}
公共接口b接口,其中T:AInterface{}
公共类Z,其中T:BInterface{}
不过,我不确定这两个地方是否都需要它。接口中的泛型参数在默认情况下是不变的,您需要明确指定您希望特定泛型参数是协变的还是逆变的。基本上,在您的示例中,您需要在接口声明中添加“out”关键字:
public interface BInterface<out T> where T : AInterface { }
公共接口b接口,其中T:AInterface{}
您可以在MSDN:上找到有关创建变量接口的详细信息。类不能是变量,因此您不能为类中的泛型参数添加“out”或“in”。谢谢Alexandra。如果T是一个返回参数,这肯定会有所帮助。在我的例子中,我错过了B和B接口中的一个重要细节:公共类B:B接口,其中T:AInterface{public T Element{get;set;}}}公共接口B接口,其中T:AInterface{T Element{get;set;}}out将无法工作,因为T既是In又是out。有什么建议吗?是的,如果对类型参数有泛型约束,则不能使其协变。这是故意的。在泛型接口中,如果类型参数满足以下条件,则可以将其声明为协变:1)类型参数仅用作接口方法的返回类型,而不用作方法参数的类型。2)类型参数不用作接口方法的泛型约束