“获取或创建” - 这个习语有固定的名称吗?

发布于 2024-08-06 02:18:47 字数 466 浏览 3 评论 0原文

好吧,考虑一下我们大多数人都多次使用过的这个常见习语(我假设):

class FooBarDictionary
{
    private Dictionary<String, FooBar> fooBars;

    ...

    FooBar GetOrCreate(String key)
    {
        FooBar fooBar;

        if (!fooBars.TryGetValue(key, out fooBar))
        {
            fooBar = new FooBar();
            fooBars.Add(key, fooBar);
        }

        return fooBar;
    }
}

它有任何既定的名称吗?

(是的,它是用 C# 编写的,但它可以“轻松”转移到 C++。因此有了这个标签。)

Ok, consider this common idiom that most of us have used many times (I assume):

class FooBarDictionary
{
    private Dictionary<String, FooBar> fooBars;

    ...

    FooBar GetOrCreate(String key)
    {
        FooBar fooBar;

        if (!fooBars.TryGetValue(key, out fooBar))
        {
            fooBar = new FooBar();
            fooBars.Add(key, fooBar);
        }

        return fooBar;
    }
}

Does it have any kind of established name?

(Yes, it's written in C#, but it can be "easily" transferred to C++. Hence that tag.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

硬不硬你别怂 2024-08-13 02:18:47

我总是调用此类函数obtainSomething()

I always call such functions obtainSomething().

猫九 2024-08-13 02:18:47

这在某种程度上取决于你这样做的原因——我见过的习惯用法被称为记忆、缓存、按需初始化、第一次使用时创建。通常我将该方法称为“ensureFoo”而不是“GetOrCreate”

It sort of depends why you're doing it - the idiom is one I've seen be called memoization, caching, initialisation on demand, create on first use. Normally I call the method "ensureFoo" rather than "GetOrCreate"

拥有 2024-08-13 02:18:47

我不确定高级模式的整体编程名称,但 Perl 有这种奇妙的行为,称为 Autovivification - 即,当您查询哈希中不存在的键的值时,自动创建具有未定义值的哈希(映射)键。

I'm unsure of overall programming name for the high level pattern, but Perl has this wonderful behavior called Autovivification - namely, automatically creating hash (map) key with undefined value when you're querying the value of non-existing key in the hash.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文