emr*_*mre 14 c# self-reference
我一直在阅读Albaharis的"C#5.0 in A Nutshell",我在Generics部分遇到过这个问题,据说这是合法的:
class Bar<T> where T : Bar<T> { ... }
Run Code Online (Sandbox Code Playgroud)
尽管我仔细阅读了整章,但这对我来说毫无意义.我甚至无法理解它.
有人可以用一些可以理解的命名来解释它,例如:
class Person<T> where T : Person<T> { ... }
Run Code Online (Sandbox Code Playgroud)
还有一个真实的应用场景,这种用法是否合适且有用?
ang*_*son 13
这意味着T必须继承Person<T>.
这是在基类中创建特定于类型的方法或属性或参数的典型方法,特定于实际后代.
例如:
public abstract class Base<T> where T : Base<T>, new()
{
public static T Create()
{
var instance = new T();
instance.Configure(42);
return instance;
}
protected abstract void Configure(int value);
}
public class Actual : Base<Actual>
{
protected override void Configure(int value) { ... }
}
...
Actual a = Actual.Create(); // Create is defined in Base, but returns Actual
Run Code Online (Sandbox Code Playgroud)