public static KeyValuePair<object, object > Cast<K, V>(this KeyValuePair<K, V> kvp)
{
return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
}
public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)
{
return (KeyValuePair<T, V>) obj;
}
public static KeyValuePair<object , object > CastFrom(Object obj)
{
var type = obj.GetType();
if (type.IsGenericType)
{
if (type == typeof (KeyValuePair<,>))
{
var key = type.GetProperty("Key");
var value = type.GetProperty("Value");
var keyObj = key.GetValue(obj, null);
var valueObj = value.GetValue(obj, null);
return new KeyValuePair<object, object>(keyObj, valueObj);
}
}
throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");
}
從OP:
而不是轉換我的整個字典,我決定保持我的目標 動態整個時間。當我用foreach訪問我的 字典的鍵和值時,我使用foreach( obj.Keys中的動態鍵),並簡單地將鍵和值轉換爲字符串。
你檢查你的對象是'IDictionary'。因此,像'(IDictionary)obj'這樣的接口將會成功。儘管如此,還有許多其他的'IDictionary'比'Dictionary'更多。所以你最好測試一下你想投射的相同類型。我同意Nikhil(answerer)在這種情況下你想使用'as'。如有需要,我可以提供詳情。 –
2012-07-20 09:54:37
一般在這裏考慮答案:http://stackoverflow.com/questions/3481923/in-c-sharp-convert-anonymous-type-into-key-value-array(例如'RouteValueDictionary') – 2015-08-03 18:27:20