我的程序允许服务器将模块发送到客户端,客户端在加载模块后将返回模块信息。服务器存储将客户端信息存储在名为“loadingModules”的列表中。当服务器收到客户端的响应时,它将从该列表中删除该信息,以指示该模块的加载操作已完成。
这里的问题是我当前的做法是循环遍历整个列表并检查两个成员是否相等(ModuleName 和 TimeStamp)。这不仅效率低下,而且使代码看起来很糟糕。 我想知道是否有某种方法可以使用这两个成员的哈希来访问字典中的模块,而不是我当前正在做的事情。
public List<ClientModule> LoadingClientModules = new();
public List<ClientModule> LoadedClientModules = new();
private void ClientModuleAdded_Callback(Packet packet)
{
ClientModule f = Utils.ByteArrayToStructure<ClientModule>(packet.Payload, 0);
Utils.Log.Information($"{_ClientInformation.ComputerUser} Loaded {f.ModuleName} TimeDateStamp: {f.TimeDateStamp} Address: {f.Address}");
LoadedClientModules.Add(f);
LoadingClientModules.RemoveAll(i => i.ModuleName == f.ModuleName && i.TimeDateStamp == f.TimeDateStamp);
OnClientModuleLoaded?.Invoke(this, f);
}
最佳答案
您可以提供自定义IEqualityComparter<ClientModule>
比较这两个属性。然后你可以将其用于 Dictionary
或者 - 这里更好 - a HashSet<ClientModule>
:
public HashSet<ClientModule> LoadingClientModules = new(new ClientModuleComparer());
public HashSet<ClientModule> LoadedClientModules = new(new ClientModuleComparer());
private void ClientModuleAdded_Callback(Packet packet)
{
ClientModule f = Utils.ByteArrayToStructure<ClientModule>(packet.Payload, 0);
LoadedClientModules.Add(f);
LoadingClientModules.Remove(f);
}
这是一个可能的实现:
public class ClientModuleComparer : IEqualityComparer<ClientModule>
{
public bool Equals(ClientModule? x, ClientModule? y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.ModuleName == y.ModuleName && y.TimeDateStamp == y.TimeDateStamp;
}
public int GetHashCode([DisallowNull] ClientModule obj)
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + obj.ModuleName.GetHashCode();
hash = hash * 23 + obj.TimeDateStamp.GetHashCode();
return hash;
}
}
}
请注意,这不再允许重复。因此,这些集合中不会有多个具有相同 ModuleName 和 TimeDateStamp 的集合。 Add
返回false
以防重复。
关于c# - 使用对象哈希的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73251178/