我不想对类构造函数进行大量重载,而是想传入 aDictionary
来动态设置变量。
// 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);
...
在构造函数中,有没有办法使用字典键(一个字符串)来确定要设置的类成员?这可以通过某种方式使用反射来完成吗?