2

我不想对类构造函数进行大量重载,而是想传入 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);
...

在构造函数中,有没有办法使用字典键(一个字符串)来确定要设置的类成员?这可以通过某种方式使用反射来完成吗?

4

4 回答 4

11

这些字段已经是公开的……为什么不直接使用对象初始化语法呢?

var p = new Project() {
    LoanName = "New Loan Name",
    LoanProgram = 1,
    ProjectAddress = "123 Whatever Way"
};
于 2013-01-24T18:12:54.330 回答
3
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);
        }
    }
}
于 2013-01-24T18:14:05.717 回答
1

这似乎是一场维护噩梦,但您可以通过这种方式查找房产。

var prop = typeof(Project).GetProperty(entry.Key);

然后你可以像这样设置值。

prop.SetValue(this, entry.Value);

但是,您不会通过这种方式进行编译时类型检查。

于 2013-01-24T18:15:51.403 回答
0

我建议查看默认参数。

例如

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
于 2013-01-24T18:14:47.900 回答