C# - Specifying type parameters of super-class in sub-classes?

懵懂的女人 提交于 2020-04-18 06:10:12

问题


I am trying to do the following in C#.

public class Parent<T> where T : Parent<???>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

How can I do it?


回答1:


This works fine:

public class Parent<T> where T : Parent<T>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

Do be careful with this as c# does not enforce a true Parent/Child relationship. For example, given the above code, it is also legal for me to then do this:

public class Stranger : Parent<Child>
{
}

If you write unit tests then it's worth writing a type checker that looks for this mispattern.



来源:https://stackoverflow.com/questions/61240804/c-sharp-specifying-type-parameters-of-super-class-in-sub-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!