我对并发词典及其所有涉及“尝试”的新方法都很陌生。我在下面编写了一个简单的方法,从字典中检索roomInformation (roomInformation是一个类),然后打印它,如果它存在,并返回true。
我做得对吗?有更好的办法吗?请务必让我知道,如果有一个更有力的替代解决方案。
public bool TryGetRoomInformation(int roomId, out RoomInformation roomInformation)
{
if (!_roomInformation.ContainsKey(roomId))
{
roomInformation = null;
return false;
}
if (_roomInformation.TryGetValue(roomId, out roomInformation))
{
return true;
}
roomInformation = null;
return false;
}使用情况:
RoomInformation roomInfo;
if (!RoomManager.TryGetRoomInformation(1, out roomInfo))
{
// didnt find anything :(
return;
}
// use roomInfo, it was found发布于 2016-10-26 15:57:34
我注意到的一件事是,您可以消除第一个if块,该条件将在稍后处理。如果密钥无效,TryGetValue将返回false,这样您只查找键一次:
public bool TryGetRoomInformation(int roomId, out RoomInformation roomInformation)
{
if (_roomInformation.TryGetValue(roomId, out roomInformation))
{
return true;
}
roomInformation = null;
return false;
}发布于 2016-10-26 16:02:26
想出最好的办法就是这样。
public bool TryGetRoomInformation(int roomId, out RoomInformation roomInformation)
{
return _roomInformation.TryGetValue(roomId, out roomInformation);
}https://codereview.stackexchange.com/questions/145327
复制相似问题