我有这个 C# 代码:
public ExpenseReportPage()
{
InitializeComponent();
}
// Custom constructor to pass expense report data
public ExpenseReportPage(object data) : this()
{
// Bind to expense report data
this.DataContext = data;
}
当我在传递一个对象的情况下调用构造函数时到底发生了什么?我似乎无法掌握事件链。如果你要传递一个对象,它也会调用另一个构造函数吗?
假设您有三个构造函数,其中两个带有 this()
。在没有 this()
的情况下调用构造函数会调用其中任何一个吗?我错过了什么吗?据我了解,强调DRY的只是构造函数重载。
本质上,它总是调用默认值?
只要对我的想法进行一些验证/纠正就会有很大的帮助。
谢谢
编辑:
如果没有要传递的 lName(第 3 个参数),它如何调用构造函数?
class Student {
string _studentType = "";
string _id = "";
string _fName = "";
string _lName = "";
public Student(string id)
: this(id, "", "") {
}
public Student(string id, string fName)
: this(id, fName, "") {
}
public Student(string id, string fName, string lName) {
//Validate logic.....
_studentType = "<student_type>";
_id = id;
_fName = fName;
_lName = lName;
}
}
编辑 2:
我现在理解了默认值,而且它更有意义。我的问题是,如果它没有所有参数,它如何调用构造函数。
最佳答案
this()
在链接执行的构造函数之前被调用。然后将调用链接构造函数。
一种常见的示例构造函数链接涉及提供合理的默认值,如下所示:
class SomeData
{
private string _string;
private int _int;
public SomeData() : this("Default", 42)
{
}
public SomeData(string str) : this(str, 42)
{
}
public SomeData(string str, int num)
{
_int = num;
_string = str;
}
}
这将允许 SomeData
的用户使用任何构造函数实例化它。
可以说,使用可选参数,可以更好地解决这个问题:
public SomeData(string str = "Default", int num = 42) { }
使用 SomeData
的链式构造函数,如果我调用 SomeData()
,则首先调用 SomeData(string, num)
。返回后,SomeData
无参数构造函数可以访问链式构造函数所做的修改。
关于C# 构造函数链接说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156037/