如果测试对象是在C#字典 [英] Testing if an Object is a Dictionary in 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屋!