使用"通用值"将对象强制转换为KeyValuePair?

taf*_*b76 2 c# casting keyvaluepair

我有一个ComboBox,里面装满了两种不同类型的混合物品.类型是

KeyValuePair<Int32, FontFamily>
Run Code Online (Sandbox Code Playgroud)

要么

KeyValuePair<Int32, String>
Run Code Online (Sandbox Code Playgroud)

现在有些时候我只对所选项目的Key感兴趣,它始终是Int32.

访问所选项目的密钥最简单的方法是什么?我在想类似的东西

Int32 key = ((KeyValuepair<Int32, object/T/var/IdontCare>)combobox.SelectedItem).Key;
Run Code Online (Sandbox Code Playgroud)

但那不起作用.

所以我只有

    Int32 key;
    if(combobox.SelectedItem.GetType().Equals(typeof(KeyValuePair<Int32, FontFamily)))
    {
        key = ((KeyValuePair<Int32, FontFamily)combobox.SelectedItem).Key;
    }
    else if(combobox.SelectedItem.GetType().Equals(typeof(KeyValuePair<Int32, String)))
    {
        key = ((KeyValuePair<Int32, String)combobox.SelectedItem).Key;
    }
Run Code Online (Sandbox Code Playgroud)

哪个有效,但我想知道是否有更优雅的方式?

Ric*_*der 6

投射到dynamic(穷人的反思)可以做到这一点

var key = (int) ((dynamic) comboxbox.SelectedItem).Key);
Run Code Online (Sandbox Code Playgroud)

  • 在项目中包含`Microsoft.CSharp`程序集. (2认同)