C#'s equivalent of Java's wildcard

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

    I believe you want to constrain type parameters to generic types - the where keyword is used for that:

    class MyDict : Dictionary where TValue : SomeBaseClass
    {
        ...
    }
    

    Is this what you're asking for or am I misunderstanding your question?

    Edit: you cannot do exactly what you ask for in C# - you can't define an local instance of a generic type with a type constraint. You can, however, pre-declare your constrained Dictionary type (like my example) and then create an instance of that type like so:

    // SomeClass will have to inherit from SomeBaseClass
    MyDict instance = new MyDict ();
    

    I think this is close to what you're looking for. Post a comment if I misunderstand it - I don't know Java this deep.

提交回复
热议问题