测试对象是否是 C# 中的字典 [英] Testing if an Object is a Dictionary in C#

查看:25
本文介绍了测试对象是否是 C# 中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法测试一个对象是否是字典?

Is there a way to test if an object is a dictionary?

在一种方法中,我试图从列表框中的选定项目中获取值.在某些情况下,列表框可​​能会绑定到字典,但这在编译时是未知的.

In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.

我想做类似的事情:

if (listBox.ItemsSource is Dictionary<??>)
{
    KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem;
    object value = pair.Value;
}

有没有办法在运行时使用反射动态地做到这一点?我知道可以对泛型类型使用反射并确定键/值参数,但我不确定在检索到这些值后是否有办法完成其余的工作.

Is there a way to do this dynamically at runtime using reflection? I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.

推荐答案

它应该类似于以下内容.我在答案框中写了这个,所以语法可能不完全正确,但我已将其设为 Wiki 可编辑,以便任何人都可以修复.

It should be something like the following. I wrote this in the answer box so the syntax may not be exactly right, but I've made it Wiki editable so anybody can fix up.

if (listBox.ItemsSource.IsGenericType && 
    typeof(IDictionary<,>).IsAssignableFrom(listBox.ItemsSource.GetGenericTypeDefinition()))
{
    var method = typeof(KeyValuePair<,>).GetProperty("Value").GetGetMethod();
    var item = method.Invoke(listBox.SelectedItem, null);
}

这篇关于测试对象是否是 C# 中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆