在父方法中返回子类 C#

Dar*_*Nik 5 c# oop

我有父类:

public abstract class ParentClass
{
     public ParentClass ParentMethod() { ... }
}
Run Code Online (Sandbox Code Playgroud)

我还有两个孩子:

public class ChildA : ParentClass
{
    public ChildA ChildAMethod1()
    {
        ... 
        return this; 
    }

    public ChildA ChildAMethod2()
    {
        ... 
        return this; 
    }
}

public class ChildB : ParentClass
{
     public ChildB ChildBMethod() { ... 
            return this; }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可以这样写:

new ChildA().ChildAMethod1().ChildAMethod2();
Run Code Online (Sandbox Code Playgroud)

但是如何实现这样写的可能性:

new ChildA().ParentMethod().ChildAMethod1().ChildAMethod2();

new ChildB().ParentMethod().ChildBMethod1();
Run Code Online (Sandbox Code Playgroud)

这种可能性还有其他模式吗?

Iva*_*uba 4

使 ParentMethod 通用

public abstract class ParentClass
{
    public T ParentMethod<T>() where T:ParentClass
    {
        return (T)this; 
    }
}
Run Code Online (Sandbox Code Playgroud)

然后称之为

new ChildA().ParentMethod<ChildA>().ChildAMethod1().ChildAMethod2();
new ChildB().ParentMethod<ChildB>().ChildBMethod1();
Run Code Online (Sandbox Code Playgroud)