を実装するインスタンスがありますが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を呼び出すこともできますが、[]演算子を呼び出すことは可能であると思います。誰か助けてもらえますか?