Can I Create a Dictionary of Generic Types?

前端 未结 10 2452
误落风尘
误落风尘 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:40

    I came to a type safe implementation using ConditionalWeakTable.

    public class FieldByType
    {
        static class Storage
            where T : class
        {
            static readonly ConditionalWeakTable table = new ConditionalWeakTable();
    
            public static T GetValue(FieldByType fieldByType)
            {
                table.TryGetValue(fieldByType, out var result);
                return result;
            }
    
            public static void SetValue(FieldByType fieldByType, T value)
            {
                table.Remove(fieldByType);
                table.Add(fieldByType, value);
            }
        }
    
        public T GetValue()
            where T : class
        {
            return Storage.GetValue(this);
        }
    
        public void SetValue(T value)
            where T : class
        {
            Storage.SetValue(this, value);
        }
    }
    

    It can be used like this:

    /// 
    /// This class can be used when cloning multiple related objects to store cloned/original object relationship.
    /// 
    public class CloningContext
    {
        readonly FieldByType dictionaries = new FieldByType();
    
        public void RegisterClone(T original, T clone)
        {
            var dictionary = dictionaries.GetValue>();
            if (dictionary == null)
            {
                dictionary = new Dictionary();
                dictionaries.SetValue(dictionary);
            }
            dictionary[original] = clone;
        }
    
        public bool TryGetClone(T original, out T clone)
        {
            var dictionary = dictionaries.GetValue>();
            return dictionary.TryGetValue(original, out clone);
        }
    }
    

提交回复
热议问题