作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码。
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/
我是一名优秀的程序员,十分优秀!