简体   繁体   中英

Return child class in parent method C#

I have parent class:

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

Also I have two childs:

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

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

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

In this case I have possibility to write like this:

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

But how to implement possibility to write like this:

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

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

Is there any other patterns to such possibility?

Make ParentMethod generic

public abstract class ParentClass
{
    public T ParentMethod<T>() where T:ParentClass
    {
        return (T)this; 
    }
}

then call it like

new ChildA().ParentMethod<ChildA>().ChildAMethod1().ChildAMethod2();
new ChildB().ParentMethod<ChildB>().ChildBMethod1();

What is the connection between parent and child class if methods of the child are not inherited from parent?

Since classes are already decoupled, you can emphasize that decoupling via an interface:

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; 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM