[Proxy]An helper for Proxy pattern
本文不是在介紹 Proxy pattern , 而是當你創建Proxy之後, 會經常遇到要填值的問題,
如果欄位少, 一對一慢慢code是沒關係, 但值一多還真是恐佈及累人,
寫了一支簡單的code 來處理, 另外因為LINQ2SQL創建出來的Entity是將值存在Property, 而非一般的Field,
故增加了ProxyMode: Field2Field, Field2Property, Property2Field, Property2Property, 前面為來源, 後者為結果
1: /// <summary>
2: /// Source 2 Target mode.
3: /// </summary>
4: public enum ProxyMode
5: {
6: Field2Field, Field2Property, Property2Field, Property2Property
7: }
1: public class StaticProxyHelper
2: {
3: /// <summary>
4: /// 將來源物件以名稱為條件映射至指定的結果物件(T).
5: /// 名稱不分大小寫. 若遇到無法映射者, 則維持原值, 不會抛出Exception
6: /// </summary>
7: /// <param name="src"></param>
8: /// <param name="mode"></param>
9: /// <returns></returns>
10: public static T proxyIt<T>(object src, ProxyMode mode)
11: {
12: Type sType = src.GetType();
13: Type tType = typeof(T);
14:
15: T target = (T) tType.GetConstructor(new Type[] { }).Invoke(null);
16:
17: switch (mode)
18: {
19: #region XXX2Field
20: case ProxyMode.Field2Field:
21: case ProxyMode.Property2Field:
22: foreach (var field in tType.GetFields())
23: {
24: if (mode == ProxyMode.Field2Field)
25: {
26: var sF = sType.GetField(field.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
27: if (sF != null)
28: {
29: field.SetValue(target, sF.GetValue(src));
30: }
31: }
32: else
33: {
34: var sP = sType.GetProperty(field.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
35: if (sP != null)
36: {
37: field.SetValue(target, sP.GetValue(src, null));
38: }
39: }
40: }
41: break;
42: #endregion
43:
44: #region XXX2Property
45: case ProxyMode.Field2Property:
46: case ProxyMode.Property2Property:
47: foreach (var property in tType.GetProperties())
48: {
49: if (mode == ProxyMode.Field2Property)
50: {
51: var sF = sType.GetField(property.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
52: if (sF != null)
53: {
54: property.SetValue(target, sF.GetValue(src), null);
55: }
56: }
57: else
58: {
59: var sP = sType.GetProperty(property.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
60: if (sP != null)
61: {
62: property.SetValue(target, sP.GetValue(src, null), null);
63: }
64: }
65: }
66: break;
67: #endregion
68: }
69:
70: return target;
71: }
72: }