原始问题
考虑以下情况:
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 属性的值设置为第二个构造函数中 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;
}
}
非常感谢您的回复。
答案 0 :(得分:9)
是的,您可以使用this
关键字在C#中调用另一个构造函数。这通常用于模拟默认参数。例如:
public class Bar : Foo
{
public int Amount { get; set; }
public Bar() : this(String.Empty) {}
public Bar(string name): this(name, 0) {}
public Bar(string name, int amount) : base(name)
{
this.Amount = amount;
}
}
答案 1 :(得分:3)
public class Bar : Foo {
public int Amount { get; set; }
public Bar() : this(null, 0) { }
public Bar(string name) : this(name, 0) { }
public Bar(string name, int amount) : base(name){
this.Amount = amount;
}
}
答案 2 :(得分:1)
public class Bar : Foo {
public int Amount { get; set; }
public Bar() : this(0) { }
public Bar(int amount) : this(String.Empty, amount) { }
public Bar(string name) : this(name, 0) { }
public Bar(string name, int amount) : base(name) {
this.Amount = amount;
}
}
或
public class Bar : Foo {
public int Amount { get; set; }
public Bar() : this(String.Empty, 0) { }
public Bar(string name) : this(name, 0) { }
public Bar(string name, int amount) : base(name) {
this.Amount = amount;
}
}
答案 3 :(得分:-1)
构造函数链接的假设是有一个构造函数执行实际工作,而其他构造函数链到那个构造函数链。通常是设置可选参数; “全部完成”的构造函数采用完整的参数列表。其他构造函数具有较短的参数列表,并在链接时传递默认值。
public class Foo : Bar
{
private bool whyFoo;
public Foo() : this(true)
{
}
public Foo(bool why) : base(why, false)
{
whyFoo = why;
}
}