gpt4 book ai didi

generics - .net 4 泛型问题

转载 作者:行者123 更新时间:2023-12-02 21:46:39 25 4
gpt4 key购买 nike

我有以下类结构:

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>();
}
}

这在 C# 4.0 中给出了以下编译错误。类型“Test.Y”不能用作泛型类型或方法“Test.Z”中的类型参数“T”。没有从“Test.Y”到“Test.BInterface”的隐式引用转换。

我认为泛型中的协方差应该可以实现这一点?任何帮助将不胜感激。

最佳答案

接口(interface)中的泛型参数默认是不变的,您需要显式指定特定的泛型参数是协变还是逆变。基本上,在您的示例中,您需要将“out”关键字添加到接口(interface)声明中:

public interface BInterface<out T> where T : AInterface { } 

您可以在 MSDN 上找到有关创建变体接口(interface)的更多信息:Creating Variant Generic Interfaces (C# and Visual Basic) .

关于generics - .net 4 泛型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1972828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com