我有一个实例实现了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, null };
bool hasElement = (bool)tryGetValue.Invoke(otherInstance, arguments);
object anotherValue = arguments[1];
}
我也可以调用TryGetValue方法,但是我认为应该可以调用[]操作符。有人能帮助我吗?