类型约束 [英] Type constraint
本文介绍了类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的类层次结构。
I have the following class hierarchy.
class Header { IEnumerable<Item> Item { get; set; } .... }
class HeaderA : Header { .... } // Item should have the type of IEnumerable<ItemA>
class HeaderB : Header { .... } // Item should have the type of IEnumerable<ItemB>
class Item { .... }
class ItemA : Item { .... }
class ItemB : Item { .... }
是否有可能有编译时检查对项目
的类型,以确保它的的IEnumerable&LT;意达&GT;
,的IEnumerable&LT; ItemB&GT;
为意达
和 ItemB
分别是多少?有没有更好的设计?
Is it possible to have compile time checking on the type of Item
to make sure it's IEnumerable<ItemA>
, IEnumerable<ItemB>
for ItemA
and ItemB
respectively? Is there any better design?
推荐答案
您可以更改标题类的定义,类型参数传递给它,那么你可以并处是:
You can change the definition of the Header class to pass the type parameter to it, then you could impose that:
class Header<TItem> where TItem : Item { IEnumerable<TItem> Item { get; set; } }
class HeaderA : Header<ItemA> { } // Item should have the type of IEnumerable<ItemA>
class HeaderB : Header<ItemB> { } // Item should have the type of IEnumerable<ItemB>
class Item { }
class ItemA : Item { }
class ItemB : Item { }
这篇关于类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文