获取一个对象的属性/属性值,以及动态给属性赋值
生活随笔
收集整理的這篇文章主要介紹了
获取一个对象的属性/属性值,以及动态给属性赋值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//定義類public class MyClass{public int Property1 { get; set; }public string Property2 { get; set; }} MyClass tmp_Class = new MyClass();tmp_Class.Property1 = 2;tmp_Class.Property2 = "aq23iu";Type type = tmp_Class.GetType(); //獲取類型System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //獲取指定名稱的屬性
//無法指定屬性的名稱時,這樣使用GetProperties()函數 遍歷 得到每個屬性的名稱(字符串)
? ?Type t = tmp_Class.GetType();
??????????? PropertyInfo[] propertyInfoArr = t.GetProperties();
??????????? foreach (PropertyInfo item in propertyInfoArr)
??????????? {
??????????????? PropertyInfo propertyInfo = t.GetProperty(item.Name); //獲取指定名稱的屬性
??????????????? var? value = propertyInfo.GetValue(tmp_Class, null); //獲取屬性值
??????????????? Console.WriteLine(value);
??????????? }
int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //獲取屬性值 Console.WriteLine(value_Old);propertyInfo.SetValue(tmp_Class, 5, null); //給對應屬性賦值int value_New = (int)propertyInfo.GetValue(tmp_Class, null);Console.WriteLine(value_New);
//無法指定屬性的名稱時,這樣使用GetProperties()函數 遍歷 得到每個屬性的名稱(字符串)
? ?Type t = tmp_Class.GetType();
??????????? PropertyInfo[] propertyInfoArr = t.GetProperties();
??????????? foreach (PropertyInfo item in propertyInfoArr)
??????????? {
??????????????? PropertyInfo propertyInfo = t.GetProperty(item.Name); //獲取指定名稱的屬性
??????????????? var? value = propertyInfo.GetValue(tmp_Class, null); //獲取屬性值
??????????????? Console.WriteLine(value);
??????????? }
int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //獲取屬性值 Console.WriteLine(value_Old);propertyInfo.SetValue(tmp_Class, 5, null); //給對應屬性賦值int value_New = (int)propertyInfo.GetValue(tmp_Class, null);Console.WriteLine(value_New);
參考:http://www.bitscn.com/pdb/dotnet/200804/138760.html
轉載于:https://www.cnblogs.com/jcdd-4041/p/4184997.html
總結
以上是生活随笔為你收集整理的获取一个对象的属性/属性值,以及动态给属性赋值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】每天一个linux命令(50):c
- 下一篇: ubuntu install fo