Testing if an Object is a Dictionary in C#

后端 未结 7 1060
傲寒
傲寒 2020-12-06 10:21

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

7条回答
  •  有刺的猬
    2020-12-06 11:13

    Check to see if it implements IDictionary.

    See the definition of System.Collections.IDictionary to see what that gives you.

    if (listBox.ItemsSource is IDictionary)
    {
        DictionaryEntry pair = (DictionaryEntry)listBox.SelectedItem;
        object value = pair.Value;
    }
    

    EDIT: Alternative when I realized KeyValuePair's aren't castable to DictionaryEntry

    if (listBox.DataSource is IDictionary)
    {
         listBox.ValueMember = "Value";
         object value = listBox.SelectedValue;
         listBox.ValueMember = ""; //If you need it to generally be empty.
    }
    

    This solution uses reflection, but in this case you don't have to do the grunt work, ListBox does it for you. Also if you generally have dictionaries as data sources you may be able to avoid reseting ValueMember all of the time.

提交回复
热议问题