延迟加载字典

问题描述 投票:0回答:2

我有一些填充两个字典的代码

void Load(out Dictionary<string, string> m1, out Dictionary<string, string> m2) { ... }

仅当我需要访问任何一个词典时才执行。由于有许多方法依赖于加载的字典,因此我不想通过调用Load来污染所有字典,例如:

void DoSomething()
{
    if(notYetInitialized) 
        Load(out this.dict1, out this.dict2);
    // do something with either dict1 or dict2
}

或者,我可以在构造函数中调用该方法。但是,这意味着在任何情况下都将调用Load,无论是否使用了两个字典中的任何一个。这就是为什么我关注Lazy的原因。但是,由于我有应该填充two参数的one方法,因此我不确定如何进行这项工作。

所以我想要实现的是这样的:

void DoSomething()
{
    var value = this.dict1[key]; // if dict1 is not yet loaded, call Load, which will also load dict2
}
c# lazy-loading
2个回答
1
投票

您可以创建自己的结构以包含两个字典,或者仅对它们两个使用元组。

然后,您可以像这样使用Lazy来初始化它们:

public sealed class Test
{
    public Test()
    {
        _dicts = new Lazy<(Dictionary<string, string> m1, Dictionary<string, string> m2)>(initDicts);
    }

    public void DoSomething()
    {
        _dicts.Value.m1.Add("key", "value");
        _dicts.Value.m2.Add("key", "value");
    }

    (Dictionary<string, string> m1, Dictionary<string, string> m2) initDicts()
    {
        return (new Dictionary<string, string>(), new Dictionary<string, string>());
    }

    readonly Lazy<(Dictionary<string, string> m1, Dictionary<string, string> m2)> _dicts;
}

1
投票

您可以使用Lazy<(Dictionary<string, string> m1, Dictionary<string, string> m2)>

private Lazy<(Dictionary<string, string> m1, Dictionary<string, string> m2)> _lazy;
private Dictionary<string, string> _dict1 => _lazy.Value.m1;    
private Dictionary<string, string> _dict2 => _lazy.Value.m2;
public SomeCtor()
{
    _lazy = new Lazy<(Dictionary<string, string> m1, Dictionary<string, string> m2)>(
          () => (new Dictionary<string, string>(), new Dictionary<string, string>())); // your actual logic to load dictionaries

}
© www.soinside.com 2019 - 2024. All rights reserved.