与其多次重载类构造函数,不如传入一个 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);
...
在构造函数中,有没有办法使用Dictionary Key(字符串)来确定要设置的类成员?这可以通过某种方式使用反射来完成吗?
最佳答案
字段已经公开了...为什么不直接使用对象初始化语法呢?
var p = new Project() {
LoanName = "New Loan Name",
LoanProgram = 1,
ProjectAddress = "123 Whatever Way"
};
关于c# - 使用字典键(作为字符串)在构造函数中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14507910/