[英]C# - Specifying type parameters of super-class in sub-classes?
I am trying to do the following in C#.我正在尝试在 C# 中执行以下操作。
public class Parent<T> where T : Parent<???>
{
public T Prop { get; set; }
}
public class Child : Parent<Child>
{
}
How can I do it?我该怎么做?
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.请注意这一点,因为 c# 不会强制执行真正的Parent
/ Child
关系。 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.如果您编写单元测试,那么值得编写一个类型检查器来查找这种错误模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.