“GetOrCreate” - does that idiom have an established name?

后端 未结 5 1290
清歌不尽
清歌不尽 2021-02-12 19:51

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

class FooBarDictionary
{
    private Dictionary fooBars;

          


        
5条回答
  •  名媛妹妹
    2021-02-12 20:33

    In C#...

    ... I've got a DefaultingDictionary<> which does about this. As a bonus

    • you can specify a default value or factory function to create values for missing keys:
    • it comes with implicit conversion from IDictionary<> (wrapping the dictionary)
    • it comes with extension methods to morph any dictionary into a DefaultingDictionary<> on the fly

    Full Code:

    • https://gist.github.com/2789882#file_defaulting_dictionary.cs

    The extensions .AsDefaulting can be used to transparently use any IDictionary<> as a defaulting one, so you can opt to use any dictionary (even e.g. obtained from a thirdparty API) as a defaulting one, and the underlying container will be updated with any 'auto-vivified' items.

    Use it like

    IDictionary dict = LoadFromDatabase();
    
    // using a fixed value
    SomeFunc(dict.AsDefaulting(defaultItem));
    
    // using an independent generator function
    var defaulting = dict.AsDefaulting(() => new MyItem { Id = System.Guid.NewGuid() });
    
    // using a keydepedent generator function
    var defaulting = dict.AsDefaulting(key => LazyLoadFromDatabase(key));
    

    Some test cases

    are included:

    • https://gist.github.com/2789882#file_defaulting_dictionary_tests.cs

提交回复
热议问题