使用字典键(作为字符串)在构造函数中设置变量
本文关键字:构造函数 变量 设置 字符串 字典 | 更新日期: 2023-09-27 17:55:57
与其对类构造函数进行大量重载,不如传入一个动态设置变量的Dictionary
。
// Class definition
public class Project
{
public DateTime LastModified;
public string LoanName;
public string LoanNumber;
public int LoanProgram;
public string ProjectAddress;
...
// Project class constructor
public Project(Dictionary<string, object> Dict)
{
foreach (KeyValuePair<string, object> entry in Dict)
{
// ie, when the Key is "LoanName", this.LoanName is set
this.(entry.Key) = entry.Value; // <-- Does not compile, obviously
}
}
}
// application code
...
Dictionary<string, object> dict = new Dictionary<string,object>();
dict.Add("LoanName", "New Loan Name");
dict.Add("LoanProgram", 1);
dict.Add("ProjectAddress", "123 Whatever Way");
Project p = new Project(dict);
...
在构造函数中,有没有办法使用字典键(字符串)来确定要设置的类成员? 这可以通过反射以某种方式完成吗?
这些字段已经是公开的...为什么不直接使用对象初始化语法?
var p = new Project() {
LoanName = "New Loan Name",
LoanProgram = 1,
ProjectAddress = "123 Whatever Way"
};
public class Project
{
public DateTime LastModified;
public string LoanName;
public string LoanNumber;
public int LoanProgram;
public string ProjectAddress;
...
// Project class constructor
public Project(Dictionary<string, object> Dict)
{
foreach (KeyValuePair<string, object> entry in Dict)
{
this.GetType().GetProperty(entry.Key).SetValue(this, entr.Value, null);
}
}
}
这似乎是一场维护噩梦,但您可以通过这种方式查找属性。
var prop = typeof(Project).GetProperty(entry.Key);
然后你可以像这样设置值。
prop.SetValue(this, entry.Value);
不过,您不会以这种方式进行编译时类型检查。
我建议查看默认参数。
例如
public Project(loanName = null, lastModified = null, loanNumber = null, loanProgram = 0, projectAddress = null)
{
//Set them in here
}
我还建议使用公共属性而不是公共字段。例如
public DateTime LastModified { get; private set; } //Makes it so only inside the class LastModified can be set