将Java中的Enumeration for循环转换成C#?在C#中,Enumeration到底是什么?

12 浏览
0 Comments

将Java中的Enumeration for循环转换成C#?在C#中,Enumeration到底是什么?

这个问题已经在这里有了答案:

如何遍历字典?

我正在将一个项目从Java转换成C#。我尝试搜索这个问题,但我找到的都是关于枚举的问题。有一个Hashtable htPlaylist,循环使用Enumeration通过键进行遍历。我该如何将这段代码转换为使用Dictionary而不是Hashtable的C#代码呢?

// My C# Dictionary, formerly a Java Hashtable.
Dictionary<int, SongInfo> htPlaylist = MySongs.getSongs();
// Original Java code trying to convert to C# using a Dictionary.
for(Enumeration e = htPlaylist.keys(); e.hasMoreElements();
{
    // What would nextElement() be in a Dictonary? 
    SongInfo popularSongs = htPlaylist.get(e.nextElement());
}

admin 更改状态以发布 2023年5月21日
0
0 Comments

嗯,只是一个 foreach 循环? 针对给定的

   Dictionary htPlaylist = MySongs.getSongs();

可以是

   foreach (var pair in htPlaylist) {
     // int key = pair.Key;
     // SongInfo info = pair.Value;
     ...
   }

或者如果你只想要键:

   foreach (int key in htPlaylist.Keys) {
     ...
   }

0