4

たとえば、基本クラスがあり、派生クラスで計算されるプロパティが必要です。2 つのバリアント (SomeProperty1SomeProperty2) があります。

public class BaseClass
{
    public int SomeProperty1{get;set;}
    public override int SomeProperty2{get;set;}
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
       SomeProperty1 = 100;
    }
    public override int SomeProperty2
    {
        get
        {
            return 100;
        }
    }
}

質問は、最善の方法は何ですか、SomeProperty1またはSomeProperty2?

4

4 に答える 4

4

と呼ばれる保護された抽象メソッドを基本クラスに追加しCalcSomeProperty()ます。

次に、 の観点からプロパティを実装しますCalcSomeProperty()。これにより、派生クラスが強制的に実装されます。

例えば:

public abstract class BaseClass
{
    public int SomeProperty
    {
        get
        {
            return CalcSomeProperty();
        }
    }

    protected abstract int CalcSomeProperty();
}

または、プロパティ自体を抽象化することもできます。

public abstract class BaseClass
{
    public abstract int SomeProperty { get; }
}

いずれの場合も、派生クラスにプロパティ計算を実装するように強制しています。

(単純な抽象プロパティを使用するのではなく) 保護されたメソッドに計算を分離する利点は、計算が遅い場合に具体的なプロパティの実装でキャッシュを実行できることです。

public abstract class BaseClass
{
    protected BaseClass()
    {
        _someProperty = new Lazy<int>(CalcSomeProperty);
    }

    public int SomeProperty
    {
        get
        {
            return _someProperty.Value;
        }
    }

    protected abstract int CalcSomeProperty();

    private readonly Lazy<int> _someProperty;
}
于 2013-04-01T09:50:34.000 に答える
0

本当に子クラスでオーバーライドするつもりなら、おそらくプロパティをvirtualにしたかったでしょう:

public virtual int SomeProperty2{get;set;}

基本クラスで宣言されたパブリック プロパティと、子クラスでオーバーライドできる保護された仮想プロパティを用意した方がよいでしょう。

// base
protected virtual int SomePropertyInternal2
{
    get
    {
        return 10;
    }
}

public int SomeProperty2
{
    get
    {
        return SomePropertyInternal2;
    }

// child
protected override int SomePropertyInternal2
{
    return 100;
}

この場合、パブリック コントラクトは変更されずに、内部実装がオーバーライドされます。

于 2013-04-01T09:57:26.863 に答える