简体   繁体   中英

C# equivalent of java Class<E> and E extends Enum<E>

I am trying to translate one Java library into C# code, and since I am new to C# (and never worked with generics until recently) I am strugling a bit...

As for Java generics, I am trying (and more or less understanding) its way of operation. Although I have checked this Why not extending from Enum<E extends Enum<E>> and this How to use Class<T> in Java? , I am not able to really understand whats going on in this piece of Java code, and, as a result, I am not able to think about an equivalent C# code.

public abstract class TraciObject<E extends Enum<E>> {
    private final String id;    
    private final EnumMap<E, ReadObjectVarQuery<?>> readQueries;    
    protected TraciObject(String id, Class<E> enumClass) {
        this.id = id;
        readQueries = new EnumMap<E, ReadObjectVarQuery<?>>(enumClass);
    }
    ...
}

My approach in C# so far is the following:

public abstract class TraciObject<E> where E : Enum<E> { //Non-generic type Enum cannot be used with type arguments
private readonly string id;

private readonly Dictionary<E, ReadObjectVarQuery<E>> readQueries;

protected TraciObject(String id, E enumClass)
{
    this.id = id;
    readQueries = new Dictionary<E, ReadObjectVarQuery<E>>(enumClass); //cannot convert from E  to 'System.Collections.Generic.IEqualityComparer'
}

When I have readQueries = new Dictionary<E, ReadObjectVarQuery<E>>(enumClass); I was trying to get the corresponding to Java's EnumMap(Class<K> keyType) , but checking the documentation about Dictionary https://msdn.microsoft.com/es-es/library/xfhwa508(v=vs.110).aspx I am not sure this is possible

From Java Doc : EnumMap(Class<K> keyType) :

Creates an empty enum map with the specified key type.

It seems the Dictionary constructor you are looking for is the parameterless one.

From MSDN :

Dictionary<TKey, TValue>() : Initializes a new instance of the Dictionary class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.

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