我有一个实现的实例IDictionary<T, K>
,我不知道编译时的T和K,并希望从中获取所有元素.我不想IEnumerable
出于某种原因使用,这将是唯一实现的非通用接口IDictionary
.
我到目前为止的代码:
// getting types
Type iDictType = instance.GetType().GetInterface("IDictionary`2");
Type keyType = iDictType.GetGenericArguments()[0];
Type valueType = iDictType.GetGenericArguments()[1];
// getting the keys
IEnumerable keys = (IEnumerable)dictType.GetProperty("Keys")
.GetValue(instance, null);
foreach (object key in keys)
{
// ==> this does not work: calling the [] operator
object value = dictType.GetProperty("Item")
.GetValue(instance, new object[] {key } );
// getting the value from another instance with TryGet
MethodInfo tryGetValue = iDictType.GetMethod("TryGetValue");
object[] arguments = new object[] { key, …
Run Code Online (Sandbox Code Playgroud)