子调用C#面向对象返回类型"this"

Sex*_*yMF 4 c# oop parent-child

我有2个类,每个类在所有函数中返回自己:

public class Parent{
   public Parent SetId(string id){
      ...
      return this
   }
}

public class Child : Parent{
   public Child SetName(string id){
      ...
      return this
   }
}
Run Code Online (Sandbox Code Playgroud)

我想启用这种API:

new Child().SetId("id").SetName("name");
Run Code Online (Sandbox Code Playgroud)

SetName因为无法访问SetId的回报Parent,并SetName为上Child.

怎么样?

Eli*_*ing 8

如果你真的想要这种流畅的行为,并且这个Parent类可以变得抽象,那么你可以像这样实现它:

public abstract class Parent<T> where T : Parent<T>
{
    public T SetId(string id) {
        return (T)this;
    }
}

public class Child : Parent<Child>
{
    public Child SetName(string id) {
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在可以写:

new Child().SetId("id").SetName("name");
Run Code Online (Sandbox Code Playgroud)