In C#: How to declare a generic Dictionary with a type as key and an IEnumerable<> of that type as value?

后端 未结 6 1281
我在风中等你
我在风中等你 2020-12-24 12:10

I want to declare a dictionary that stores typed IEnumerable\'s of a specific type, with that exact type as key, like so: (Edited to follow johny g\'s comment)<

6条回答
  •  半阙折子戏
    2020-12-24 12:48

    You may not even need a dictionary to be able to do this - but that depends on your needs. If you only ever need 1 such list per type per appdomain (i.e. the "dictionary" is static), the following pattern can be efficient and promotes type-inference nicely:

    interface IBase {}
    
    static class Container {
        static class PerType where T : IBase {
            public static IEnumerable list;
        }
    
        public static IEnumerable Get() where T : IBase 
            => PerType.list; 
    
        public static void Set(IEnumerable newlist) where T : IBase 
            => PerType.list = newlist;
    
        public static IEnumerable GetByExample(T ignoredExample) where T : IBase 
            => Get(); 
    }
    

    Note that you should think carefully before adopting this approach about the distinction between compile-time type and run-time type. This method will happily let you store a runtime-typed IEnumerable variable both under SomeType and -if you cast it- under any of SomeType's base types, including IBase, with neither a runtime nor compiletype error - which might be a feature, or a bug waiting to happen, so you may want an if to check that.

    Additionally, this approach ignores threading; so if you want to access this data-structure from multiple threads, you probably want to add some locking. Reference read/writes are atomic, so you're not going to get corruption if you fail to lock, but stale data and race conditions are certainly possible.

提交回复
热议问题