C#'s equivalent of Java's wildcard

前端 未结 3 612
生来不讨喜
生来不讨喜 2021-01-21 04:53

If it exists, what is the C# equivalent of the following Java code:

new HashMap, Integer>();

I currently

3条回答
  •  离开以前
    2021-01-21 05:29

    There is no equivalent of the Java wildcard in C#. In Java, the type for types is Class where T is the class itself. The equivalent in C# is the type Type, which is not generic. So it seems that the best you can do is to have, as you said, a Dictionary, and if it's encapsulated in a class you can restrict what you put in the dictionary in the code (so it will just be a runtime check):

    private Dictionary myDictionary = new Dictionary();
    public void Add(Type type, int number) {
       if (!typeof(BaseClass).IsAssignableFrom(type)) throw new Exception();
       myDictionary.Add(type, number);
    }
    

    You can even implement your own IDictionary with that logic.

    UPDATE

    Another runtime trick I can think of is to use a wrapper class for your types:

    public class TypeWrapper
    {
        public Type Type { get; private set; }
        public TypeWrapper(Type t)
        {
            if (!typeof(T).IsAssignableFrom(t)) throw new Exception();
            Type = t;
        }
        public static implicit operator TypeWrapper(Type t) {
            return new TypeWrapper(t);
        }
    }
    

    (Also implement Equals and GetHashCode, just delegate to Type.)

    And then your dictionary becomes:

    var d = new Dictionary, int>();
    d.Add(typeof(BaseClass), 2);
    d.Add(typeof(Child), 3);
    

提交回复
热议问题