情境:
我需要在同一段程式碼內
讀取N種不同Key Value型態的Dictionary
我完全無法預期對方會怎樣搞這個Dictionary的Key Value型態
我該怎樣做?
技巧重點:
本文假設您已經能做到將這個不知道型態的Dictionary
透過C#的System.Reflection技巧從你需要的地方抽取出來
成為一個object型態的Dictionary物件
(如果您仍無法辦到這樣的處理, 請再多找一些C#Reflection相關技巧的文章, 這篇幅略多了)
以下我們直接上code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ObjToDictionary | |
{ | |
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this object obj) | |
{ | |
var stringDictionary = obj as Dictionary<TKey, TValue>; | |
if (stringDictionary!= null) | |
{ | |
return stringDictionary; | |
} | |
var baseDictionary = obj as IDictionary; | |
if (baseDictionary != null) | |
{ | |
var dictionary = new Dictionary<TKey, TValue>(); | |
foreach (DictionaryEntry keyValue in baseDictionary) | |
{ | |
if (!(keyValue.Value is TValue)) | |
{ | |
// value is not TKey. perhaps throw an exception | |
return null; | |
} | |
if (!(keyValue.Key is TKey)) | |
{ | |
// value is not TValue. perhaps throw an exception | |
return null; | |
} | |
dictionary.Add((TKey)keyValue.Key, (TValue)keyValue.Value); | |
} | |
return dictionary; | |
} | |
// object is not a dictionary. perhaps throw an exception | |
return null; | |
} | |
} |
請注意, 這段Code還使用了C#的Extension Function技巧
這段code是參考這篇文章, 5樓的Simon改出來的
他原本的設計是普通的function call
我則進一步改成object身上的Extension Function
準備完成, 開始進行操作:
現在假設我已經準備好了一個名為originalObj的Dictionary物件
object originalObj = 使用Reflection技巧GetField().GetValue()取出Dictionary物件為object;
Dictionary<object, object> myDictionary = originalObj.ToDictionary<object, object>();
ok, 這樣我們就拿到一個無論是key或value都是object型態的Dictionary了
剩下的就是依需求去使用這個Dictionary了
沒有留言:
張貼留言