我有一个ICollection
,我知道只会有一个成员。目前,我通过循环,知道循环将只运行一次,以获取价值。有没有更干净的方法来做到这一点?C#:轻松访问单身ICollection <>的成员?
我可以改变persistentState对象来返回单个值,但这会使接口的其余部分复杂化。它从XML中获取数据,并且大部分ICollection
是合适的。
// worldMapLinks ensured to be a singleton
ICollection<IDictionary<string, string>> worldMapLinks = persistentState.GetAllOfType("worldMapLink");
string levelName = ""; //worldMapLinks.GetEnumerator().Current['filePath'];
// this loop will only run once
foreach (IDictionary<string, string> dict in worldMapLinks) // hacky hack hack hack
{
levelName = dict["filePath"];
}
// proceed with levelName
loadLevel(levelName);
这里是同一个问题的另一个例子:
// meta will be a singleton
ICollection<IDictionary<string, string>> meta = persistentState.GetAllOfType("meta");
foreach (IDictionary<string, string> dict in meta) // this loop should only run once. HACKS.
{
currentLevelName = dict["name"];
currentLevelCaption = dict["teaserCaption"];
}
另一个例子:
private Vector2 startPositionOfKV(ICollection<IDictionary<string, string>> dicts)
{
Vector2 result = new Vector2();
foreach (IDictionary<string, string> dict in dicts) // this loop will only ever run once
{
result.X = Single.Parse(dict["x"]);
result.Y = Single.Parse(dict["y"]);
}
return result;
}
+1更好的答案 - 'Single'是这里的最佳选择。 :) – 2010-03-17 18:17:27