gpt4 book ai didi

c# - 泛型基类的派生类型

转载 作者:行者123 更新时间:2023-11-30 13:17:15 25 4
gpt4 key购买 nike

我有以下代码。

class Header<T> where T: IItem { }
class HeaderA : Header<ItemA> { }
class HeaderB : Header<ItemB> { }

interface IItem { }
class ItemA : IItem { }
class ItemB : IItem { }

Header<IItem> h = new HeaderA();

最后一行无法编译。

Cannot implicitly convert type 'UserQuery.HeaderA' to 'UserQuery.Header<UserQuery.IItem>'

HeaderA 是 Header 的子类型,ItemA 是 IItem 的子类型。为什么它不起作用?

最佳答案

简而言之,您正在尝试使用一个名为协方差 的概念,.NET generic classes 不支持它。 , 默认不支持 interfaces .

如果您想允许类执行此操作,您可以在 C# 3 或更高版本中使用 out contextual keyword 指定它。在 generic interface 上:

interface IHeader<out T> where T : IItem { }
class Header<T>: IHeader<T> where T:IItem { }
class HeaderA : Header<ItemA> { }
class HeaderB : Header<ItemB> { }

interface IItem { }
class ItemA : IItem { }
class ItemB : IItem { }

public void Foo()
{
//now this works; notice the use of the interface instead of the base class.
IHeader<IItem> h = new HeaderA();
}

通过使用带有关键字的接口(interface),您基本上是在告诉编译器,接口(interface)的任何使用都不必了解更多关于 generic type 的信息。比它满足接口(interface)的通用类型声明的约束(或者它是一个对象)。因此,虽然您现在可以将更多派生泛型分配给接口(interface)类型的变量,但您只能将它们作为接口(interface)类型来处理,而不能作为任何派生类型来处理。

out 类定义不接受关键字;您不能强制使用 Header<T>是协变的。

关于c# - 泛型基类的派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12431246/

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