假设我有一个Customer具有几个属性 ( ID, FirstName, LastName) 的对象。我有默认构造函数Customer(),但我也有一个Customer(DataRow dr),因为我从数据库加载这个对象,这是一种简单的方法。
我经常遇到想要设置另一个构造函数的情况,Customer(int ID)有时我想加载 aCustomer但我还没有访问数据库。对我来说最简单的方法似乎是这样的:
Customer(int ID)
{
DataTable dt = DataAccess.GetCustomer(ID);
if (dt.Rows.Count > 0)
{
// pass control to the DataRow constructor at this point?
}
else
{
// pass control to the default constructor at this point?
}
}
重用已经存在于 DataRow 构造函数中的代码是有意义的,但是我想不出一种方法来调用它并返回它给我的东西。通过谷歌搜索,我找到了有关使用: this()语法重载构造函数的信息,但所有这些示例似乎都与我正在尝试做的事情背道而驰或不兼容。
所以我对构造函数的理解存在差距,但我似乎无法理清。我错过了什么?