C#類的屬性遍歷及屬性值獲取

寫代碼時,遇到一個問題,需要獲取一個類的所有屬性。當然可以在類裏面寫一個靜態函數,手動去獲取。 但是類的屬性變了,又去更新這個函數,實在麻煩。網上查了查相關資料。自己整理了一些使用心得。

1、定義一個類

public class Person
{
     public string Name { get; set; }
     public int ID { get; set; }
}

2、獲取屬性

方法一、定義一個類的對象獲取

Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
    Console.WriteLine(info.Name);
}

方法二、通過類獲取

var properties = typeof(Person).GetProperties();
foreach (System.Reflection.PropertyInfo info in properties)
{
   Console.WriteLine(info.Name);
}

3、通過屬性名獲取屬性值

p.Name = "張三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);

4、完整代碼及結果顯示

var properties = typeof(Person).GetProperties();
foreach (System.Reflection.PropertyInfo info in properties)
{
   Console.WriteLine(info.Name);
}
Console.WriteLine("另一種遍歷屬性的方法:");

Person p = new Person();
foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties())
{
   Console.WriteLine(info.Name);
}
            
 Console.WriteLine("通過屬性值獲取屬性:");

p.Name = "張三";
var name = p.GetType().GetProperty("Name").GetValue(p, null);
Console.WriteLine(name);
Console.ReadLine();



















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章