如何从基类型中声明的方法返回派生类型

本文关键字:类型 方法 返回 派生 声明 基类 | 更新日期: 2023-09-27 18:10:22

我在基类中有一个方法,它应该返回类型的self实例作为派生类型。例如:

class A
{
   public string X { get; set; }
   public A SetX(string x)
   {
       this.X = x;
       return this;
   }
}
class B:A
{
   public string Y { get; set; }
   public B SetY(string y)
   {
       this.Y = y;
       return this;
   }
}

然后我想像下面这样流畅地调用方法:

B b = new B();
b.SetX("x")
 .SetY("y");

但是这里SetX返回A的类型,并且A没有任何名为SetY的方法。我如何设计这样的功能?

如何从基类型中声明的方法返回派生类型

一种选择是将SetX声明为通用扩展方法:

public static T SetX<T>(this T a, string x) where T : A
{
    a.X = x;
    return a;
}

你可以这样调用它:

var newB = b.SetX("foo"); // returns type B

你可以做一些不同的事情来达到这个目的。

第一种是使用泛型,使用类型参数指定实例的实际类型:

public class A<T> where T:A<T>
{
    public string X { get; private set; }
    public T SetX(string x)
    {
        X = x;
        return (T) this;
    }
}
public class B<T> : A<T>
    where T : B<T>
{
    public string Y { get; private set; }
    public T SetY(string y)
    {
        Y = y;
        return (T) this;
    }
}
public class A : A<A>
{
}
public class B : B<B>
{
}

第二个是在B类中,使用new关键字对A隐藏方法,如下所示:

class A
{
    public string X { get; set; }
    public A SetX(string x)
    {
        this.X = x;
        return this;
    }
}
class B : A
{
    public string Y { get; set; }
    public new B SetX(string x)
    {
        return (B) base.SetX(x);
    }
    public B SetY(string y)
    {
        this.Y = y;
        return this;
    }
}

use protected:

protected string X { get; set; }
protected A SetX(string x)
{
   this.X = x;
   return this;
}

这个很适合我:

(b.SetX("1") as B).SetY("2");