使用反射获取通用 IDictionary 的值
我有一个实现 IDictionary
的实例,我在编译时不知道 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,但我认为应该可以调用 [] 运算符。 有谁能够帮助我?
I have an instance that implements IDictionary<T, K>
, I don't know T and K at compiletime, and want to get all elements from it. I don't want to use IEnumerable
for some reason, which would be the only non-generic interface implemented by IDictionary
.
Code I have so far:
// 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];
}
I could also call TryGetValue, but I think it should be possible to call the [] operator. Can anybody help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好找出
TKey
/TValue
,并通过MakeGenericMethod
切换到常规代码 - 就像这样:(编辑 - 如果它们属于同一类型,您也可以将
otherInstance
作为参数传递)It would be better to figure out the
TKey
/TValue
, and switch into regular code viaMakeGenericMethod
- like so:(edit - you could pass in the
otherInstance
as an argument too, if they are of the same type)只是为了完成,即使 Marc Gravell 的解决方案更好,这就是它的工作方式,就像我已经开始的那样:
这调用字典的 [] 运算符。
Just for completion, even if Marc Gravell's solution is much nicer, this is the way how it works the way I already started:
This calls the [] operator of the dictionary.