轉自:http://blog.csdn.net/lanx_fly/article/details/53914338
背景簡介
之前看過一些代碼,是簡單的讀取SqlReader而後賦值給Model,我不是不贊同這種作法,只是看到大篇幅的賦值操做真的有點浪費時間和精力,尤爲是一些老項目居多。我看到的還好,多的也就60多個字段且不用其餘ORM,若是涉及到變動的話,那麼對維護人員來講可能不只僅是眼力活甚至仍是....體力活。另外就是表格的操做,由於鄙人以前也是寫過相似的項目,列名對應着Model屬性名,一個不差,隱隱以爲它們之間應該聯繫起來,因此想能不能儘量簡化它的操做?多是本身作得項目太少,只能想到反射這種方法,可是反射的性能你們也都瞭解,大量的反射賦值耗時能夠慢到你眨幾下眼睛,但這對程序來講我以爲是一場災難。所以結合反射發出的方法寫了這個庫,若是能給你們在項目上帶來一些便利我也就滿足了。html
案例1:
- public class Student : INMSReflector {
- public string Name;
- public string Description { get; set; }
- public static string StaticField;
- public static string StaticProperty { get; set; }
- }
引用步驟:
- Step1 : 引用類庫.
- Step2 : using NMSReflector.
- Step3 : 將你的類實現INMSReflector接口;(固然了,若是你嫌麻煩,能夠改一下源碼,在ModelOperator.cs中).
- Step4 : 用Create方法建立緩存. (會掃描搜索入口程序集的全部類)
因爲類庫中對object類型作了擴展,所以對象實例能夠調用擴展方法。git
一、EmitSet(string propertyName,object value) 爲對象的字段或屬性賦值github
二、EmitGet(string propertyName) 獲取對象某字段或者屬性值 緩存
用法:
- ModelOperator.Create();
- Student t = new Student();
- t.Name = "小明";
- t.EmitSet("Name", "小明胸前的紅領巾更加鮮豔了!");
- Console.WriteLine(t.Name);
- Console.WriteLine(t.EmitGet("Name"));
- t.EmitSet("Description", "他愛着小剛");
- Console.WriteLine(t.Description);
- Console.WriteLine(t.EmitGet("Description"));
- t.EmitSet("StaticFiled", "是他挨着小剛");
- Console.WriteLine(Student.StaticField);
- Console.WriteLine(t.EmitGet("StaticField"));
- t.EmitSet("StaticProperty", "剛纔打錯了");
- Console.WriteLine(Student.StaticProperty);
- Console.WriteLine(t.EmitGet("StaticProperty"));
結果:
案例2:
支持Column標籤
- public class Student : INMSReflector
-
- {
-
- public string Name;
-
- [Column("Note")]
-
- public string Description { get; set; }
-
- public static string StaticField;
-
- public static string StaticProperty { get; set; }
-
- }
注意:
- 這裏的標籤是來自於System.ComponentModel.DataAnnotations.Schema;
- 因此須要using System.ComponentModel.DataAnnotations.Schema;
用法:
不管傳標籤設置的名字仍是屬性名,均可以賦值或者獲取值。
- ModelOperator.Create();
- Student t = new Student();
- t.EmitSet("Note", "設置標籤");
- Console.WriteLine(t.Description);
- Console.WriteLine(t.EmitGet("Note"));
結果:
其餘:
ModelOperator類提供了更多的操做函數。
- 與object的擴展方法有所不一樣,第一個參數須要把實例傳進去
- object Get<T>(T t, string propertyName)
- void Set<T>(T t, string propertyName, object value)
- Type GetType<T>(string propertyName)
- Dictionary<string, Action<object, object>> GetSetCache<T>()
- Dictionary<string, Func<object, object>> GetGetCache<T>()
- Dictionary<string, Type> GetTypeCache<T>()
- Dictionary<string, string> GetMapCache<T>()