C#映射類獲取類中屬性名稱與屬性的值

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Tool;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            People model = new People();
            model.PeopleName = "張三";
            model.PeopleAge = 18;
            model.PeopleAddress = "中國上海";


            foreach (PropertyInfo info in model.GetType().GetProperties())
            {
                string Name = info.Name;

                object value = info.GetValue(model, null);

                if (info.PropertyType.IsValueType || info.PropertyType.Name.StartsWith("String"))
                {
                    Console.WriteLine("字段屬性名稱: {0} => 字段屬性值: {1}", Name, value.ToString());
                }
                //info.SetValue(model, "設置遍歷該字段的值", null);
            }

            Console.ReadKey();
        }

      
        public class People
        {
            public string PeopleName { get; set; }

            public int PeopleAge { get; set; }

            public string PeopleAddress { get; set; }
        }

    }
}

 

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