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

複製代碼Type t = tc.GetType();//獲得該類的Type

//再用Type.GetProperties獲得PropertyInfo[],然後就可以用foreach 遍歷了
foreach (PropertyInfo pi in t.GetProperties
{
object value1 = pi.GetValue(tc, null));//用pi.GetValue獲得值
string name = pi.Name;//獲得屬性的名字,後面就可以根據名字判斷來進行些自己想要的操作
//獲得屬性的類型,進行判斷然後進行以後的操作,例如判斷獲得的屬性是整數
if(value1.GetType() == typeof(int))
{
//進行你想要的操作
}
}
public int Pid
{
get { return pid; }
set { pid = value; }
}

 

 

//****************

  public void InitialProperty()//初始化設定
        {
            System.Reflection.PropertyInfo[] properties = this.GetType().GetProperties();
            foreach(var v in properties)
            {
               string type= v.PropertyType.Name;
                if (type=="String")
                {
                    v.SetValue(this,"456",null);
                }
                else if(type=="Bitmap")
                {
                    v.SetValue(this, new Bitmap(Image.FromFile("1.png")), null);
                }
               

            }
           

        }

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