我正在使用 C#.Net 和 SQL Server 编写桌面应用程序。我有几个带有几个参数的 calss 构造函数,每次我都应该将它们传递给它们。下面是一个例子:
Classes.Prices prices = new Classes.Prices
(comboBox1.SelectedValue.ToString(),
Convert.ToInt32(txtPrice.Text),
Convert.ToInt32(txtCarbohydrate.Text),
Convert.ToInt32(txtProtein.Text),
Convert.ToInt32(txtFat.Text),
Convert.ToInt32(txtHumidity.Text),
Convert.ToInt32(txtminerals.Text));
有什么方法可以克服这个问题并防止为转换和传递多个参数编写太多代码 到构造函数?
最佳答案
您不应在一个方法中使用超过 2 到 3 个参数。
定义一个名为PriceHolder
的类
public class PriceHolder
{
public string FirstValue { get; set; }
public string Price { get; set; }
public string Carbohydrate { get; set; }
public string Protein { get; set; }
public string Fat { get; set; }
public string Humidity { get; set; }
public string Minerals { get; set; }
}
然后,您的构造函数必须接受 PriceHolder
像这样:
public Prices(PriceHolder hold)
{
// access the values by hold.Fat, hold.Minerals etc
}
此方法使重构代码更容易,或者如果您打算添加更多属性。
此外,您的程序员同事将能够轻松理解它。可读性很重要!
关于c# - 优化多个参数传递给类构造函数的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22593329/