在父类方法中返回子类 C#

4

我有一个父类:

public abstract class ParentClass
{
     public ParentClass ParentMethod() { ... }
}

此外,我有两个子元素:
public class ChildA : ParentClass
{
    public ChildA ChildAMethod1()
    {
        ... 
        return this; 
    }

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

public class ChildB : ParentClass
{
     public ChildB ChildBMethod() { ... 
            return this; }
}

在这种情况下,我有可能像这样写:
new ChildA().ChildAMethod1().ChildAMethod2();

但是如何实现像这样写作的可能性:
new ChildA().ParentMethod().ChildAMethod1().ChildAMethod2();

new ChildB().ParentMethod().ChildBMethod1();

有其他模式可以实现这种可能性吗?

ParentMethod是否也返回此对象,或者它可以是任何ParentClass类型的对象? - oliver
2个回答

4
使ParentMethod通用化
public abstract class ParentClass
{
    public T ParentMethod<T>() where T:ParentClass
    {
        return (T)this; 
    }
}

然后像这样调用它
new ChildA().ParentMethod<ChildA>().ChildAMethod1().ChildAMethod2();
new ChildB().ParentMethod<ChildB>().ChildBMethod1();

是的,这就是我要找的。我稍微修改了一下。只是将其改为 public abstract class ParentClass<T> 然后 public class ChildA : ParentClass<ChildA> public class ChildB : ParentClass<ChildB>并在子类方法中返回T。 谢谢! - DarkNik

0

如果子类的方法没有从父类继承,那么父类和子类之间有什么联系?

由于类已经解耦,您可以通过接口强调这种解耦:

public interface INext
{
    INext ChildAMethod1();
    INext ChildAMethod2();
}

public abstract class ParentClass
{
    public INext ParentMethod()
    {
        ...
        return new ChildA(...);
    }
}

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接