【问题标题】:How can I set my class properties values Using Reflection如何使用反射设置我的类属性值
【发布时间】:2017-11-24 03:17:16
【问题描述】:

美好的一天,

假设这是我的课:

public class MyClass {

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

这是我的字典:

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

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

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

方法参数应该是这样的:

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

谢谢

【问题讨论】:

    标签: c# reflection uwp


    【解决方案1】:

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

    【讨论】:

    • 谢谢,顺便说一句,我的方法在 MyClass 里面,我得到 String 不能转换为 Boolean ,如何自动转换呢?我传递的总是字符串,因为它来自后端
    • @NicoTing 用转换器改变了答案
    • TypeDescriptor 不存在,不建议命名空间,顺便说一句,我正在开发 uwp 应用程序,已经包含 using System.ComponentModel;
    • @NicoTing 抱歉,我帮不上忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多