Base class constraint on generic class specifying the class itself

后端 未结 3 1794
南旧
南旧 2021-01-17 15:54

Yesterday, I was explaining C#\'s generic constraints to my friends. When demonstrating the where T : CLASSNAME constraint, I whipped up something like this:

3条回答
  •  抹茶落季
    2021-01-17 16:12

    If any of these is possible, what would the type of T be?

    They are all possible, and you are the one who is gonna determine what is the type of T.For example let's assume there is a type that inherits from UnusableClass

    class Foo : UnusableClass { }
    

    Now you can instantiate UnusableClass because Foo satisfies the constraint:

    UnusableClass f = new UnusableClass();
    

    Then the type of T become Foo and if you try to call method you need to pass an instance of Foo.

提交回复
热议问题