Type constraint

2019-07-02 13:59发布

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 { .... }

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?

5条回答
对你真心纯属浪费
2楼-- · 2019-07-02 14:18

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 { }
查看更多
Lonely孤独者°
3楼-- · 2019-07-02 14:18

Like this

class HeaderA : Header<ItemB> { .... }
class HeaderB : Header<ItemA> { .... }
查看更多
够拽才男人
4楼-- · 2019-07-02 14:20

If I understand your question correctly, you can change the signatures of the Header class to accomplish this.

class Header<ItemType> { IEnumerable<ItemType> Item {get; set;} ....}
class HeaderA : Header<ItemA> { .... }
class HeaderB : Header<ItemB> { .... }

class Item { .... }
class ItemA : Item { .... }
class ItemB : Item { .... }

would result in HeaderA only allowing ItemA objects and HeaderB only allowing ItemB objects to be put into their respective Item collections.

查看更多
疯言疯语
5楼-- · 2019-07-02 14:24

You should use a Generic Class

查看更多
一纸荒年 Trace。
6楼-- · 2019-07-02 14:31

You can use a generic type and pass it to the class.

public class Header<T> where T : Item
{
   IEnumerable<T> Item { get; set; }
}


 Header<ItemA> AHeader;
 Header<ItemB> BHeader;

http://msdn.microsoft.com/en-US/library/sz6zd40f(v=vs.100)

查看更多
登录 后发表回答