c# 反射获取Dictionary
///
/// 反射获得键值对类型的,key的TypeFullName和value的TypeFullName.
///
///
///
///
static void GetReflexDictionaryKeyValueTypeFullName(object dictionaryVal, out string keyType, out string valueType)
{
keyType = "";
valueType = "";
Type type = dictionaryVal.GetType();
bool b = type.IsGenericType;
Type IDictionaryType = type.GetInterface("IDictionary", false);
if (b && IDictionaryType != null)
{
//获取集合属性的值的属性
PropertyInfo countPro = type.GetProperty("Count");
PropertyInfo keyPro = type.GetProperty("Keys");
PropertyInfo ValuesPro = type.GetProperty("Values");
//获取对应的值
object objKey = keyPro.GetValue(dictionaryVal);
object objValue = ValuesPro.GetValue(dictionaryVal);
//获取索引Get方法
MethodInfo keyGet = objKey.GetType().GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);
keyType = keyGet.ReturnType.FullName;
MethodInfo valuesGet = objValue.GetType().GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);
valueType = valuesGet.ReturnType.FullName;
}
}
///
/// 反射获得键值对类型的,key的TypeFullName和value的TypeFullName.
///
///
///
///
///
///
static Dictionary
//获取对应的值
count = (int)countPro.GetValue(dictionaryVal);
object objKey = keyPro.GetValue(dictionaryVal);
object objValue = ValuesPro.GetValue(dictionaryVal);
//获取索引Get方法
MethodInfo keyGet = objKey.GetType().GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);
keyType = keyGet.ReturnType.FullName;
MethodInfo valuesGet = objValue.GetType().GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);
valueType = valuesGet.ReturnType.FullName;
for (int i = 0; i < count; i++)
{
result.Add(keyGet.Invoke(objKey, new Object[] { i }), valuesGet.Invoke(objValue, new Object[] { i }));
}
}
return result;