相关疑难解决方法(0)

使用反射获取通用IDictionary的值

我有一个实现的实例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)

c# generics reflection idictionary

9
推荐指数
2
解决办法
8229
查看次数

标签 统计

c# ×1

generics ×1

idictionary ×1

reflection ×1