繁体   English   中英

C#-多态问题

[英]C# - polymorphism question

我有一些类,我希望使用链方法来提供流畅的配置样式。

例如

public class BaseFoo
{
    private bool _myProp = false;
    public [[[BaseFoo?]]] SetMyProperty()
    {
        this._myProp = true;
        return this;
    }
}

public class DerivedFoo : BaseFoo
{
    public bool _derivedProp = false;
    public DerivedFoo SetDerivedPropery()
    {
        this._derivedProp = true;
        return this;
    }
}

问题很明显是在尝试将它们链接在一起时,一旦我使用base方法返回了BaseFoo的类型。 显然,我可以将其转换回DerivedFoo,但是有一种简单的方法可以返回派生类类型的对象。

我能想到的唯一方法是将构造函数链接在一起,然后将父类型传递给初始构造函数,但会使用语法。

另一种方法是为每个子类具有类似的代理方法,但返回派生类型。

 DerivedFoo foo = new DerivedFoo();
        foo.SetMyProperty().SetDerivedPropery(); // wont work because the SetMyProperty returns type of BaseFoo
        foo.SetDerivedPropery().SetMyProperty(); // works because I know i'm calling the method of the derived class first
        (foo.SetMyProperty() as DerivedFoo).SetDerivedPropery(); // works as i'm casting result of base method to derived type

有任何想法吗?

提前致谢,

山姆

泛型呢?

public class BaseFoo<TDerived> where TDerived : BaseFoo<TDerived>
{
    private bool _myProp = false;
    public TDerived SetMyProperty()
    {
        this._myProp = true;
        return (TDerived)this;
    }
}

public class DerivedFoo : BaseFoo<DerivedFoo>
{
    public bool _derivedProp = false;
    public DerivedFoo SetDerivedPropery()
    {
        this._derivedProp = true;
        return this;
    }
}

但是我确实认为继承层次结构的不同级别之间的耦合是一个很大的设计问题。
我建议您看看其他流利的界面,例如Fluent NHibernate,Rhino Mocks等,以了解“大个子”们是如何做到的;-)

您也可以使用这种扩展方法,这是一种流畅的升级 对我来说这似乎更干净。

public static class FooFluentExtensions
{
    public static T SetMyProperty<T>(this T foo) where T : BaseFoo
    {
        foo.MyProp = true;
        return foo;
    }

    public static T SetDerivedPropery<T>(this T foo) where T : DerivedFoo
    {
        foo.DerivedProp = true;
        return foo;
    }
}

static void Main()
{
    DerivedFoo foo = new DerivedFoo();
    // works, because SetMyProperty returns DerivedFoo
    foo.SetMyProperty().SetDerivedPropery();

    BaseFoo baseFoo = new BaseFoo();
    baseFoo.SetMyProperty();

    // doesn't work (and that's correct), because SetMyProperty returns BaseFoo
    // baseFoo.SetMyProperty().SetDerivedPropery();
}

您可以封装所有想要流利的方法。

我个人讨厌这种编码风格。

不能让它们成为属性吗? 那你可以做

DerivedFoo foo = new DerivedFoo
{
  MyProperty = true,
  DerivedProperty = true
};

它更干净,更易读。

一种选择是执行以下操作:

public class BaseFoo<T> where T : class
{
    private bool _myProp = false;
    public T SetMyProperty()
    {
        this._myProp = true;
        return this as T;
    }
}

    public class DerivedFoo : BaseFoo<DerivedFoo> { ... }

但这取决于您的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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