使用Dictionary Key(作为字符串)在构造函数中设置变量

时间:2013-01-24 18:10:16

标签: c# reflection

我想传递一个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(一个字符串)来确定要设置的类成员?可以用某种方式使用反射来完成吗?

4 个答案:

答案 0 :(得分:11)

字段已经公开...为什么不使用对象初始化语法?

var p = new Project() {
    LoanName = "New Loan Name",
    LoanProgram = 1,
    ProjectAddress = "123 Whatever Way"
};

答案 1 :(得分: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);
        }
    }
}

答案 2 :(得分:1)

这似乎是一场维护噩梦,但你可以这样查看房产。

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

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

prop.SetValue(this, entry.Value);

虽然没有编译时间类型检查。

答案 3 :(得分:0)

我建议查看默认参数。

e.g。

public Project(loanName = null, lastModified = null, loanNumber = null, loanProgram = 0, projectAddress = null)
{
    //Set them in here
}

我还建议使用公共属性而不是公共字段。 e.g。

public DateTime LastModified { get; private set; } //Makes it so only inside the class LastModified can be set