使用反射获取通用 IDictionary 的值

发布于 2024-07-20 10:44:10 字数 1034 浏览 8 评论 0原文

我有一个实现 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

往事风中埋 2024-07-27 10:44:10

最好找出 TKey / TValue,并通过 MakeGenericMethod 切换到常规代码 - 就像这样:(

编辑 - 如果它们属于同一类型,您也可以将 otherInstance 作为参数传递)

static class Program
{
    static void Main()
    {
        object obj = new Dictionary<int, string> {
            { 123, "abc" }, { 456, "def" } };

        foreach (Type iType in obj.GetType().GetInterfaces())
        {
            if (iType.IsGenericType && iType.GetGenericTypeDefinition()
                == typeof(IDictionary<,>))
            {
                typeof(Program).GetMethod("ShowContents")
                    .MakeGenericMethod(iType.GetGenericArguments())
                    .Invoke(null, new object[] { obj });
                break;
            }
        }
    }
    public static void ShowContents<TKey, TValue>(
        IDictionary<TKey, TValue> data)
    {
        foreach (var pair in data)
        {
            Console.WriteLine(pair.Key + " = " + pair.Value);
        }
    }    
}

It would be better to figure out the TKey / TValue, and switch into regular code via MakeGenericMethod - like so:

(edit - you could pass in the otherInstance as an argument too, if they are of the same type)

static class Program
{
    static void Main()
    {
        object obj = new Dictionary<int, string> {
            { 123, "abc" }, { 456, "def" } };

        foreach (Type iType in obj.GetType().GetInterfaces())
        {
            if (iType.IsGenericType && iType.GetGenericTypeDefinition()
                == typeof(IDictionary<,>))
            {
                typeof(Program).GetMethod("ShowContents")
                    .MakeGenericMethod(iType.GetGenericArguments())
                    .Invoke(null, new object[] { obj });
                break;
            }
        }
    }
    public static void ShowContents<TKey, TValue>(
        IDictionary<TKey, TValue> data)
    {
        foreach (var pair in data)
        {
            Console.WriteLine(pair.Key + " = " + pair.Value);
        }
    }    
}
抱猫软卧 2024-07-27 10:44:10

只是为了完成,即使 Marc Gravell 的解决方案更好,这就是它的工作方式,就像我已经开始的那样:

object value = dictType.GetMethod("get_Item")
  .Invoke(instance, new object[] { key });

这调用字典的 [] 运算符。

Just for completion, even if Marc Gravell's solution is much nicer, this is the way how it works the way I already started:

object value = dictType.GetMethod("get_Item")
  .Invoke(instance, new object[] { key });

This calls the [] operator of the dictionary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文