如何设置我的类属性值使用反射

时间:2017-11-24 03:17:16

标签: c# reflection uwp

美好的一天,

让我们说这是我的班级:

public class MyClass {

    public bool boolProp { get; set; }
    public string stringProp { get; set; }
}

这是我的IDictionary:

IDictionary<string, string> myDict= 
        new IDictionary<string, string>();

myDict.Add("boolProp", "true");
myDict.Add("stringProp", "teststring");

所以我想使用Reflection更新我的类属性,其中我的字典键与属性名称匹配,然后通过创建方法设置其值,这是怎么回事?

方法参数应如下所示:

public void UpdateProperties(IDictionary<string, string> myDict) {

由于

1 个答案:

答案 0 :(得分:3)

使用GetProperty方法:

IDictionary<string, string> myDict = new Dictionary<string, string>();

myDict.Add("boolProp", "true");
myDict.Add("stringProp", "teststring");

var s = new MyClass();
var t = s.GetType();

foreach (var values in myDict)
{
    var p = t.GetProperty(values.Key, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

    var c = TypeDescriptor.GetConverter(p.PropertyType);
    var convertedValue = c.ConvertFromInvariantString(values.Value);

    p.SetValue(s, convertedValue);
}