天天看點

動态屬性(PropertyInfo)示例

//動态屬性擷取PropertyInfo

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

using System.Collections;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            List<Test> list = new List<Test>() { new Test(){Name="zfl",Age=25},new Test(){Name="lcj",Age = 25}};

            list.ForEach(t =>

                   // Console.WriteLine("Name:"+t.Name+",Age="+t.Age)

                    Write(t)

                );

            Console.Read();   

        }

        static void Write(object a)

        {

           PropertyInfo[] pros = a.GetType().GetProperties();//1.擷取所有公共的屬性集合

           int i = 0;

          foreach(PropertyInfo pro in pros)

          {

              object obj = pro.GetValue(a, null);//2.擷取值

              //pro.Name ; //擷取屬性的名稱

              //pro.PropertyType; //擷取屬性的資料類型如(System.String)

              var v = obj; //用var 定義變量,進行資料的動态接收,var的類型根據obj 的GetType()類型來決定

                Console.WriteLine( v);

                i++;

            }

        }

    }

    class Test

    {

        public String Name { get; set; }

        public int Age { get; set; }

    }

}