1. 程式人生 > 其它 >c#編碼技巧(五):用泛型T實現遍歷類的屬性-遍歷任意類的屬性

c#編碼技巧(五):用泛型T實現遍歷類的屬性-遍歷任意類的屬性

技術標籤:C#c#.net泛型

本例項程式碼演示瞭如何利用泛型T,遍歷任意類的所有屬性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericT
{
    class Program
    {
        /// <summary>
        /// 本例項程式碼演示瞭如何利用泛型T,遍歷任意類的所有屬性
        /// </summary>
        /// <param name="args"></param>
        private static string Property2String<T>(T model)
        {
            //獲取例項的type
            Type t = model.GetType();

            //把所有屬性轉化為list
            var list = t.GetProperties().ToList();
            string text = string.Empty;

            //遍歷屬性
            list.ForEach(x =>
            {
                object value = x.GetValue(model);

                //屬性值和屬性名轉為字串
                var str = string.Format(" [{0}={1}] ", x.Name, value.ToString());
                text += str;
            });
            return text;
        }
        static void Main(string[] args)
        {
            //使用方法

            //遍歷Student類的所有屬性
            var text = Property2String<Student>(new Student() { Name = "Levi", Id = "abcd", Age = 18 });
            Console.WriteLine(text);

            //遍歷School類的所有屬性
            text = Property2String<School>(new School() { Name = "college", Address = "beijing", ClassCount = 99 });
            Console.WriteLine(text);
            Console.Read();
        }
    }

    //純屬性的類
    public class Student
    {
        public string Name { get; set; }
        public string Id { get; set; }
        public int Age { get; set; }
    }

    //純屬性的類
    public class School
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public int ClassCount { get; set; }
    }
}

輸出: