异构字典,但类型化? [英] Heterogeneous Dictionary, but typed?

查看:91
本文介绍了异构字典,但类型化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是更比一个实际的问题的学术研究。是否有任何语言或框架功能,可以,或将在未来的,允许异构的类型化dcitionary,例如:

This is more of an academic inquiry than a practical question. Are there any language or framework features that can, or will in future, allow a heterogeneous typed dcitionary, e.g.

myDict.Add("Name", "Bill"); 
myDict.Add("Height", 1.2);

在这里myDict现在包含不是两个对象类型的值,而是一个字符串和一个?然后我可以取回我的

where myDict now contains not two object types as values, but one string and one double? I could then retrieve my double with

double dbl = myDict["Height"];

和预期的双重或异常被抛出?

and expect a double or an exception to be thrown?

请注意:名称和高度的值是相同的对象不一定

Please note: The Name and Height values are not necessarily of the same object.

推荐答案

你就可以,如果你有一个自定义的收集与通用重载Add和Get方法来做到这一点的唯一方法。但是,这将意味着你可以读出关键的时候问了错误的类型,所以它不会得到你多少(如果有的话)在做投自己,当你打电话给你的Get方法。

The only way you'll be able to do this if you have a custom collection with generic overloads for Add and Get methods. But that would mean you can ask for the wrong type when reading the key out, so it doesn't gain you much (if anything) over doing the cast yourself when you call your Get method.

不过,如果你可以把泛型类型插入钥匙,然后可以工作。喜欢的东西(未经测试code这里)

However, if you can push the generic type into the key then that could work. Something like (untested code here)

sealed class MyDictionaryKey<T>
{
}

class MyDictionary
{
    private Dictionary<object, object> dictionary = new Dictionary<object, object>();

    public void Add<T>(MyDictionaryKey<T> key, T value)
    {
        dictionary.Add(key, value);
    }

    public bool TryGetValue<T>(MyDictionaryKey<T> key, out T value)
    {
      object objValue;
      if (dictionary.TryGetValue(key, out objValue))
      {
        value = (T)objValue;
        return true;
      }
      value = default(T);
      return false;
    }

    public T Get<T>(MyDictionaryKey<T> key)
    {
      T value;
      if (!TryGetValue(key, out value))
         throw new KeyNotFoundException();
      return value;
    }
}

然后,你可以这样定义你的钥匙:

Then you can define your keys like:

static readonly MyDictionaryKey<string> NameKey = new MyDictionaryKey<string>();
static readonly MyDictionaryKey<double> HeightKey = new MyDictionaryKey<double>();

和使用它像

var myDict = new MyDictionary();
myDict.Add(NameKey, "Bill"); // this will take a string
myDict.Add(HeightKey , 1.2); // this will take a double

string name = myDict.Get(NameKey); // will return a string
double height = myDict.Get(HeightKey); // will return a double

这篇关于异构字典,但类型化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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