元の質問
次のシナリオを検討してください。
public abstract class Foo
{
public string Name { get; set; }
public Foo()
{
this.Name = string.Empty;
}
public Foo(string name)
{
this.Name = name;
}
}
public class Bar : Foo
{
public int Amount { get; set; }
public Bar()
: base()
{
this.Amount = 0;
}
public Bar(string name)
: base(name)
{
this.Amount = 0;
}
public Bar(string name, int amount)
: base(name)
{
this.Amount = amount;
}
}
それらの間でコードの重複がないように、構築を連鎖させるよりエレガントな手段はありますか? この例では、コードを複製して、Bar.Amountプロパティの値を2 番目のコンストラクターのamountパラメーターの値に設定する必要があります。クラス内の変数の数が増えると、構築のための順列が非常に複雑になる可能性があります。それはちょっと面白いにおいがします。
この問題に関する検索の最初の数ページをふるいにかけましたが、具体的な結果は得られませんでした。これが古い帽子だったらごめんなさい。
前もって感謝します。
アップデート
それで、私はそれについて後ろ向きに考えていました、そして以下が私のアプローチであるべきです:
public abstract class Foo
{
public string Name { get; set; }
public string Description { get; set; }
public Foo()
: this(string.Empty, string.Empty) { }
public Foo(string name)
: this(name, string.Empty) { }
public Foo(string name, string description)
{
this.Name = name;
this.Description = description;
}
}
public class Bar : Foo
{
public int Amount { get; set; }
public bool IsAwesome { get; set; }
public string Comment { get; set; }
public Bar()
: this(string.Empty, string.Empty, 0, false, string.Empty) { }
public Bar(string name)
: this(name, string.Empty, 0, false, string.Empty) { }
public Bar(string name, int amount)
: this(name, string.Empty, amount, false, string.Empty) { }
public Bar(string name, string description, int amount, bool isAwesome, string comment)
: base(name, description)
{
this.Amount = amount;
this.IsAwesome = isAwesome;
this.Comment = comment;
}
}
返信ありがとうございます。