简体   繁体   中英

Reflection Initialize Property Values of an object Instance Using

I have an Object instance. In the Object's Constructor, I would like to allow user to pass in a Dictionary with which to initialize, some, if not all of the properties of the object. Now, instead of using a conditional, what I would like to do is using reflection, reflect over the properties contained in the object instance, and if the property name, maps to a key in the dictionary, update the property value with the corresponding value in the Dictionary.

In working on this, I have the following code, but it does not update the value of my object instance. Would appreciate some help getting this to work please?

 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);
                    }
                }

            }
        }

First, have you attached a debugger to inspect whether or not you're getting inside the most nested if ? And if you're not getting inside the most nested if , can you figure out why by comparing what you expect to be happening to what is actually happening when you inspect in the debugger?

Second, inside the most nested if , you can remove the first two lines, and replace property with propertyInfo in the third line (which will be the only line remaining when you remove the first two). You already have the PropertyInfo with the given name in hand, why are you looking it up again?

Beyond that, it looks like what you have should work. Thus, there error lies elsewhere, meaning you aren't passing in the right values, or something else that you're not telling us about is going on.

Here is a small working example of what you have that should help you:

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
    }
}

Notice that it's exactly your logic and it works . Does this help?

Does it work any better if you switch it up and do?

    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");
                }
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM