Can I Create a Dictionary of Generic Types?

前端 未结 10 2439
误落风尘
误落风尘 2020-11-30 02:53

I\'d like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:

Dict         


        
10条回答
  •  清歌不尽
    2020-11-30 03:30

    Would something like this work?

    public class GenericDictionary
    {
        private Dictionary _dict = new Dictionary();
    
        public void Add(string key, T value) where T : class
        {
            _dict.Add(key, value);
        }
    
        public T GetValue(string key) where T : class
        {
            return _dict[key] as T;
        }
    }
    

    Basically it wraps all the casting behind the scenes for you.

提交回复
热议问题