【发布时间】:2016-06-14 07:53:16
【问题描述】:
我在java中有一个泛型类定义为:
public static class KeyCountMap<T>
{
private Map<T, MutableInt> map = new LinkedHashMap<T, MutableInt>();
// ... rest of the properties...
public KeyCountMap()
{ }
@SuppressWarnings({ "unchecked", "rawtypes" })
public KeyCountMap(Class<? extends Map> mapType) throws InstantiationException, IllegalAccessException
{
map = mapType.newInstance();
}
//... rest of the methods...
}
我在 .NET 中定义了相同的类:
public static class KeyCountMap<T>
{
private Dictionary<T, MutableInt> map = new Dictionary<T, MutableInt>();
// ... rest of properties...
public KeyCountMap()
{ }
public void KeyCountMap<T>(T obj) where T : Dictionary<T, MutableInt>
{
obj = new T(); // Unable to define new instance of T
map = obj; // Unable to convert T to base class
}
}
然后定义了一个方法,将KeyCountMap<T>类型的map按值降序排序。方法定义为:
public static KeyCountMap<T> SortMapByDescendValue<T>(KeyCountMap<T> _map)
{
List<KeyValuePair<T, MutableInt>> _list = new List<KeyValuePair<T, MutableInt>>(_map.EntrySet());
// whereas _map.EntrySet() return of type HashSet<KeyValuePair<T, MutableInt>>
_list = _list.OrderByDescending(_x => _x.Value).ToList();
KeyCountMap<T> _result = new KeyCountMap<T>();
foreach (KeyValuePair<T, MutableInt> _entry in _list)
{
_result.Put(_entry.Key, _entry.Value);
}
return _result;
}
如何更正 .NET 中定义的类?
【问题讨论】:
-
这样做的目的是什么?请注意,哈希表/地图/字典不保证任何顺序。您是否将 Java 音译为 C#?如果有,为什么?
-
是的,为了我的项目需求,我正在音译
-
@acelent 我已经评论了你的回答(已接受),请看一下
-
@acelent 我是来应你的聊天邀请的。你在吗?
-
@acelent 你不在你邀请的聊天室里?你什么时候到?
标签: java c# generics inheritance instantiation