Why aren't generic type constraints inheritable/hierarchically enforced

后端 未结 4 628
故里飘歌
故里飘歌 2020-11-29 06:15

Item class

public class Item
{
    public bool Check(int value) { ... }
}

Base abstract class with generic type constraint

         


        
4条回答
  •  离开以前
    2020-11-29 06:43

    Because the ClassBase has a constraint on his template (should by typeof Item), you have to add this constraint to MyClass too. If you don't do this, you could create a new instance of MyClass, where the template isn't a type of Item. When creating the base class, it will fail.

    [edit] Hmm now a re-read your question, and I see your code does compile? Ok.

    Well, im MyClass you don't know the basetype of this.items, so you can't call the Check method. this.items is of the type IList, and in your class, TItem isn't specified, thats why the class doesn't understand the Check method.

    Let me counter your question, why don't you want to add the constraint to your MyClass class? Given any other class type as template to this class, would result in an error. Why not prevent this errors by adding a constraint so it will fail compiletime.

提交回复
热议问题