私は、1つの基本クラスから派生したいくつかのクラスが必要です。基本クラスには、同じ基本クラスから派生した子クラスのリストも含まれます。C#派生クラスにプロパティセッターを追加するには?
すべてのクラスは、クラス自体から取得することができる特定の値を取得できる必要があります。または、派生クラスの種類によって親クラスになります。
プロパティではなくメソッドを使用して調べましたが、レポートエンジンで公開されている公開プロパティに直接アクセスする.NETレポートコンポーネントで値を使用したいので、メソッドの使用を除外します。
私の質問は、BaseClassの中で一般に入手可能なセッターを持たずにDerivedClassでセッターを実装するための「ベストプラクティス」メソッドであるものである
public class BaseClass
{
private BaseClass _Parent;
public virtual decimal Result
{
get { return ((_Parent != null) ? _Parent.Result : -1); }
}
}
public class DerivedClass : BaseClass
{
private decimal _Result;
public override decimal Result
{
get { return _Result; }
// I can't use a setter here because there is no set method in the base class so this throws a build error
//set { _Result = value; }
}
}
私は(次のように)で保護されたセッターを追加することはできません。 BaseClassはDerivedClassのアクセス修飾子を変更できないためです。
public class BaseClass
{
private BaseClass _Parent;
public virtual decimal Result {
get { return ((_Parent != null) ? _Parent.Result : -1); }
protected set { }
}
}
public class DerivedClass : BaseClass
{
private decimal _Result;
public override decimal Result
{
get { return _Result; }
// This setter throws a build error because of a change of access modifiers.
//set { _Result = value; }
}
}
は私がベースから派生BaseClassのか、他のクラスからプロパティを設定する機能を望んでいないとセッターとBaseClassのにメンバ変数を追加する必要はありません。
public class BaseClass
{
private BaseClass _Parent;
protected Decimal _Result; // This could result in a lot of unnecessary members in BaseClass.
public virtual decimal Result {
get { return _Result; }
// Empty setter ahead :) This does nothing.
// I could also throw an exception here but then issues would not be found until runtime
// and could cause confusion in the future with new developers etc.
set { }
}
}
public class DerivedClass : BaseClass
{
public override decimal Result
{
get { return base.Result; }
set { base._Result = value; }
}
}
その他の提案?
http://stackoverflow.com/questions/6749022/adding-a-setter-to-a-derived-interface(正確には重複しない)も参照してください。 –