调用超类方法后调用子类方法

时间:2017-08-14 23:23:44

标签: c# generics inheritance subclass superclass

最后,我想在调用超类方法之后调用子类方法。我有一个像这样的代码:

Select (CASE WHEN len(item) <= 36 THEN item
             ELSE LEFT(item, LEN(item)-36)
        END)
from dbo.fnsplit(@manager, ',')

我想做这样的事情:

public class SuperClass
{
    protected WrapperClass<T> GetWrapperClass<T>()
    {
        return new WrapperClass(someStuff).Wrap<T>();
    }

    public SuperClass CommonMethod1()
    {
        // Do something
        return this;
    }

    public SuperClass CommonMethod2()
    {
        // Do something else
        return this;
    }

    // Many CommonMethods
}

public class SubClass : SuperClass
{
    public WrapperClass<SomeClass> OptionalLastMethod1()
    {
        return base.GetWrapperClass<SomeClass>();
    }

    public WrapperClass<SomeOtherClass> OptionalLastMethod2()
    {
        return base.GetWrapperClass<SomeOtherClass>();
    }
}

我想避免像这样将SuperClass转换为SubClass:

new SubClass()
    .CommonMethod1()
    .CommonMethod2()      // Returns SuperClass
    .OptionalLastMethod1();  // I would like to do something like this.

这里的重点是易用性,不易实现。任何意见都表示赞赏。

1 个答案:

答案 0 :(得分:0)

通过这样做解决了这个问题。 - 删除了一些不相关的代码。

public class SuperClass<S> where S : SuperClass<S>
{
    public S CommonMethod1()
    {
        // Do something
        return (S) this;
    }

    public S CommonMethod2()
    {
        // Do something else
        return (S) this;
    }

    // Many CommonMethods
}

public class SubClass : SuperClass<SubClass>
{
    public WrapperClass<SomeClass> OptionalLastMethod1()
    {
        return base.GetWrapperClass<SomeClass>();
    }

    public WrapperClass<SomeOtherClass> OptionalLastMethod2()
    {
        return base.GetWrapperClass<SomeOtherClass>();
    }
}