简体   繁体   English

C#相当于Java类 <E> 和E扩展枚举 <E>

[英]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... 我正在尝试将一个Java库转换为C#代码,并且由于我是C#的新手(直到最近才使用过泛型),所以我有点挣扎...

As for Java generics, I am trying (and more or less understanding) its way of operation. 至于Java泛型,我正在尝试(或多或少了解)其操作方式。 Although I have checked this Why not extending from Enum<E extends Enum<E>> and this How to use Class<T> in Java? 尽管我已经检查了为什么不从Enum <E扩展到Enum <E >>以及如何在Java中使用Class <T>? , 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. ,我无法真正理解这段Java代码中发生的事情,因此,我无法考虑等效的C#代码。

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: 到目前为止,我在C#中的方法如下:

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); 当我有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 我试图获取与Java的EnumMap(Class<K> keyType) ,但查看有关字典的文档https://msdn.microsoft.com/es-es/library/xfhwa508(v=vs.110).aspx我不确定这是否可能

From Java Doc : EnumMap(Class<K> keyType) : Java DocEnumMap(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. 似乎您要查找的Dictionary构造函数是无参数的。

From MSDN : 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. Dictionary<TKey, TValue>() :初始化Dictionary类的新实例,该实例为空,具有默认的初始容量,并使用默认的相等比较器作为键类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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