简体   繁体   中英

Multiclass generic collection in C#

I need a typesafe multitype collection, eg, a map that maps from a generic tag class Tag<T> to an object of type T . In Java, I would have written something like this:

class ClassMap {
    private HashMap<Tag<?>,?> map = new HashMap<>();

    <T> void put(Tag<T> tag, T value){
        map.put(tag,value);
    }

    <T> get(Tag<T> tag){
        return (T) map.get(tag);
    }
}

The collection is type safe, ie, the cast (T) will always succeed as the collection checks that the class corresponds to the tag on insertion.

But how to do this in C#? Afaik, there are no wildcards in C#, so I cannot write HashMap<Tag<?>,?> here. How can I tell C# that I need a generic map but cannot exactly specify its parameters?

Have you tried this? All classes of C# are derived from object .

EDIT : Object class reference -

http://msdn.microsoft.com/en-us/library/system.object.aspx

You can typecast any object to object type -

    class Tag<T>{

    }
    class ClassMap {
        private Dictionary<object, object> map = new Dictionary<object,object>();

        public void put<T>(Tag<T> tag, T value){
            map.Add(tag, value);
        }

        public T get<T>(Tag<T> tag){
            return (T)map[tag];
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            ClassMap v = new ClassMap();
            Tag<Int16> t = new Tag<short>();
            v.put<short>(t, 10);
            var tt = v.get<short>(t);
        }
    }

The debug info -

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM