繁体   English   中英

将对象转换为具有“通用值”的 KeyValuePair?

[英]Cast object to KeyValuePair with "generic value"?

我有一个 ComboBox,里面装满了两种不同类型的混合项目。 类型是

KeyValuePair<Int32, FontFamily>

或者

KeyValuePair<Int32, String>

现在有些时候我只对所选项目的 Key 感兴趣,它总是一个 Int32。

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

Int32 key = ((KeyValuepair<Int32, object/T/var/IdontCare>)combobox.SelectedItem).Key;

但这不起作用。

所以我只有

    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;
    }

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

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

var key = (int) ((dynamic) comboxbox.SelectedItem).Key);

您当然不需要使用GetType() 你可以使用:

int key;
var item = combobox.SelectedItem;
if (item is KeyValuePair<int, FontFamily>)
{
    key = ((KeyValuePair<int, FontFamily>) item).Key;
}
else if (item is KeyValuePair<int, string>)
{
    key = ((KeyValuePair<int, string>) item).Key;
}

我不认为没有使用反射或动态类型的确有更好的方法,假设您无法将所选项的类型更改为您自己的KeyValuePair与某些非泛型基类型或接口。

我想它在WPF中受到限制,在这种情况下我建议不要使用KeyValuePair<TKey,TValue>而是使用自己的VM类。 例如

class MyComboItem
{
    private String _stringValue;
    private FontFamiliy _fontFamilyValue;

    public Int32 Key {get;set;}
    public object Value => (_fontFamilyValue!=null)?_fontFamilyValue:_stringValue;
}

或者你可以有一个像这样的界面

interface IMyComboItem
{
    Int32 Key {get;}
    object Value {get;}
}

并实现两个实现它的VM类,存储适当的值类型。 有适当的构造函数等。 无法通过泛型来实现您想要实现的转换,并且您的解决方案案例并不优雅。

您可以像这样创建自己的类层次结构

public interface IComboBoxItem
{
    public int Key { get; }
}

public class ComboBoxItem<T> : IComboBoxItem
{
    public T Value { get; set; }

    public int Key { get; set; }
}

你的演员表看起来像这样:

key = ((IComboBoxItem)combobox.SelectedItem).Key;

基于 Rich 的回答,我成功地使用了 Dynamic。 我知道我绑定到的字典类型(实际上可以使用字典本身,因为它仍然在我的表单中引用),但我想创建一个方法来按显示名称进行搜索。 这最终将检查绑定源是否也是数据表,但就目前而言,这对 <string,?> 字典很有效。

private void SetComboBoxSelection(ComboBox cmb, string ItemText)
        {
            if (cmb.DisplayMember.ToLower() == "key" && cmb.ValueMember.ToLower() == "value")
            {
                foreach (dynamic item in cmb.Items)
                    if (item.Key == ItemText)
                        cmb.SelectedItem = item.Value;
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM