C# generics contraints propagation

后端 未结 4 1695
小蘑菇
小蘑菇 2021-02-10 05:57

This example is a simplification of the real problem, but how can I get this to compile? I would expect the generics constraints to propagate.

Since T is a TClass and TC

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 06:33

    The problem is that T doesn't have to be a reference type. Consider:

    MyClass foo = new MyClass();
    MyClass.Func();
    

    That would try to call FuncA but int doesn't obey the : class constraint.

    So basically you need to add the : class constraint to Func as well:

    public void Func() where T : class, TClass
    

提交回复
热议问题