Base class constraint on generic class specifying the class itself

后端 未结 3 1754
南旧
南旧 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 16:21

    Well.

    public class Implementation : UnusableClass
    {
    }
    

    is perfectly valid, and as such makes

    var unusable = new UnusableClass();
    

    and

    UnusableClass.method(new Implementation());
    

    valid.

    So, yes, it can be instantiated by supplying an inheriting type as the type parameter, and similarly with the call to the static method. It's for instance useful for tree-like structures where you want to generically specify the type of children the node has, while it being the same type itself.

提交回复
热议问题