C#'s equivalent of Java's wildcard

前端 未结 3 611
生来不讨喜
生来不讨喜 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:31

    Was looking into this same problem and this poor man's checker is the best thing I could come up with:

    class MyValue {
        public Type Type { get; private set; }
    
        private MyValue(Type type)
        {
            this.Type = type;
        }
    
        public MyValue of() where T : BaseClass
        {
            return new MyValue(typeof(T));
        }
    }
    
    IDictionary myDictionary = new Dictionary()
    {
        { 1, MyValue.of(); },
        { 2, MyValue.of(); },
        { 3, MyValue.of(); }, // this causes a compile error
    };
    

提交回复
热议问题