C#4.0中字典元素的getter

Jps*_*psy 3 c# getter dictionary

我想实现一个字典,只有在访问它们时(而不是提前)才能动态创建自己的元素.为此,我想使用getter方法,但我根本找不到任何有关如何在字典元素的上下文中声明getter的信息.

我确实理解如何将getter添加到整个字典中(在调用时必须返回一个字典),但我想要做的是实现一个getter,当访问字典中的单个元素时调用它,这样我就可以创建该元素在飞行中.该getter必须接收用于请求的密钥作为参数,并且必须返回相应的值.

我在文档中找不到该任务的任何语法.

kev*_*kev 5

你只需要重新实现索引器 Dictionary<,>

    public class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    public new TValue this[TKey key]
    {
        get
        {
            TValue value;
            if (!TryGetValue(key, out value))
            {
                value = Activator.CreateInstance<TValue>();
                Add(key, value);
            }
            return value;
        }
        set { base[key] = value; }
    } 
}
Run Code Online (Sandbox Code Playgroud)

如果需要更复杂的值实例化,可以使用激活器功能

 public class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    readonly Func<TKey, TValue> _activator;

    public MyDictionary(Func<TKey, TValue> activator)
    {
        _activator = activator;
    }

    public new TValue this[TKey key]
    {
        get
        {
            TValue value;
            if (!TryGetValue(key, out value))
            {
                value = _activator(key);
                Add(key, value);
            }
            return value;
        }
        set { base[key] = value; }
    } 
}
Run Code Online (Sandbox Code Playgroud)

用法:

static void Main(string[] args)
{
    var dict = new MyDictionary<int, string>(x => string.Format("Automatically created Value for key {0}", x));
    dict[1] = "Value for key 1";
    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine(dict[i]);
    }
    Console.Read();
}
Run Code Online (Sandbox Code Playgroud)