[英]How can I set my class properties values Using Reflection
美好的一天,
可以說這是我的課:
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");
所以我想使用反射來更新我的類屬性,其中我的字典鍵與屬性名稱匹配,然后通過創建方法設置其值,這是怎么回事?
方法參數應如下所示:
public void UpdateProperties(IDictionary<string, string> myDict) {
謝謝
使用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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.