Why aren't generic type constraints inheritable/hierarchically enforced

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

Item class

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

Base abstract class with generic type constraint

         


        
4条回答
  •  旧时难觅i
    2020-11-29 06:32

    I think you're confused becuase you're declaring you derived class with TItem as well.

    If you think about it if you were using Q instead so.

    public class MyClass : BaseClass
    {
     ...
    }
    

    Then how is it to be determined that Q is of the type item?

    You need to add the constraint to the derived classes Generic Type as well so

    public class MyClass : BaseClass were Q : Item { ... } 
    

提交回复
热议问题