頭腦風暴之 反射+泛型 構建 普通通用功能


地球人都知道 構建通用的功能 泛型和反射是必不可少的,然后現在很多人都用ORM實體框架+泛型也可以構建

但其內部也是通過反射實現的。

解開迷霧 見天日吧。

---c#代碼

 public class Boy
    {
        public int BoyId { get; set; }
        public string BoyName { get; set; }
    }

    public class Girl
    {
        public int GirlId { get; set; }  
        public string GirlName { get; set; }
    }
    class Program
    {
        static IDictionary<object, object> GetList<T>()  where T : class
        {
            Type modelType = typeof(T);
            //創建T對象
            T model = (T)Activator.CreateInstance(modelType);
            //T model = Activator.CreateInstance<T>();
            Type t = model.GetType();
            //獲取T對象的所有屬性
            PropertyInfo[] props = t.GetProperties();
            //將屬性名稱作為key,屬性值作為value
            Dictionary<object, object> dict = new Dictionary<object, object>();
            foreach (PropertyInfo prop in props)
            {
                //獲取屬性的名稱
                string propName = prop.Name;

                //為model對象的pro屬性設置值
                //如果此屬性類型是int就賦值10
                if (prop.PropertyType==typeof(Int32))
                {   //在實際開發中 一般用 DataRow獲取數據庫相應的字段值如 dr[propName]
                    prop.SetValue(model, 10, null);
                }
                else //如果此屬性類型 不是 int就統一賦值"aaa"
                {
                    prop.SetValue(model, "aaa", null);
                }
                //獲取model中是屬性值
                object propValue=prop.GetValue(model, null);
                dict.Add(propName,propValue.ToString());
            }
            return dict;
        }
        static void Main(string[] args)
        {

            foreach (var item in GetList<Boy>())
            {
                Console.WriteLine(item.Key+":"+item.Value);
            }
            Console.WriteLine("success");
            Console.ReadKey();
        }
    }

---運行結果

---泛型約束
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM