反射初始化对象实例的属性值使用

时间:2013-06-21 21:18:53

标签: c# reflection

我有一个Object实例。在Object的构造函数中,我想允许用户传入一个Dictionary来初始化该对象的一些(如果不是全部)属性。现在,我想要做的不是使用条件,而是使用反射,反映对象实例中包含的属性,如果属性名称映射到字典中的键,则使用相应的值更新属性值在字典中。

在处理此问题时,我有以下代码,但它不会更新我的对象实例的值。我很感激能帮到这个吗?

 public void Initialize()
        {
            if (Report.GlobalParameters != null)
            {
                PropertyInfo[] propertyInfos = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    if (Report.GlobalParameters.ContainsKey(propertyInfo.Name))
                    {
                        Type type = this.GetType();
                        PropertyInfo property = type.GetProperty(propertyInfo.Name);
                        property.SetValue(this, Report.GlobalParameters[propertyInfo.Name], null);
                    }
                }

            }
        }

2 个答案:

答案 0 :(得分:3)

首先,您是否附加了一个调试器来检查您是否进入了最嵌套的if?如果你没有进入最嵌套的if,你可以通过比较你期望发生的事情和你在调试器中检查时实际发生的事情来找出原因吗?

其次,在最嵌套的if内,您可以删除前两行,并将property替换为第三行中的propertyInfo(这将是您剩下的唯一一行删除前两个)。您已经拥有了具有给定名称的PropertyInfo,为什么还要查找它?

除此之外,看起来就像你应该工作的那样。因此,错误存在于其他地方,这意味着你没有传递正确的价值观,或者你没有告诉我们的其他事情。

以下是您应该帮助您的small working example

using System;
using System.Collections.Generic;

class Foo {
    public int Bar { get; set; }
    public Foo(Dictionary<string, object> values) {
        var propertyInfo = this.GetType().GetProperties();
        foreach(var property in propertyInfo) {
            if(values.ContainsKey(property.Name)) {
                property.SetValue(this, values[property.Name], null);
            }
        }
    }
}

class Program {
    public static void Main(String[] args) {
        Dictionary<string, object> values = new Dictionary<string, object>();
        values.Add("Bar", 42);
        Foo foo = new Foo(values);
        Console.WriteLine(foo.Bar); // expect 42
    }
}

请注意,这正是您的逻辑,works。这有帮助吗?

答案 1 :(得分:-1)

如果你把它切换起来会有效吗?

    public void Initialize()
    {
        if (Report.GlobalParameters != null)
        {
            foreach (KeyValuePair<string, object> kvp in Report.GlobalParameters)
            {
                PropertyInfo pi = this.GetType().GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance);
                if (pi != null)
                {
                    try
                    {
                        pi.SetValue(this, kvp.Value, null);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(kvp.Key + Environment.NewLine + ex.ToString(), "Error Setting Property Value");
                    }
                }
                else
                {
                    MessageBox.Show(kvp.Key, "Property Not Found");
                }
            }
        }
    }
相关问题