c# - 使用对象哈希的字典

标签 c#

我的程序允许服务器将模块发送到客户端,客户端在加载模块后将返回模块信息。服务器存储将客户端信息存储在名为“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/

相关文章:

c# - Request_ResourceNotFound调用/v1.0/me

c# - ASP.NET中母版页的OnError方法的异常处理

c# - 散列对象集 C#

c# - 有人可以解释一下这段 HtmlAgilityPack 代码吗?

c# - 如何获取完整路径?

c# - WPF/数据网格 : Binding to different properties for displaying and editing

c# - 该类型不能用作泛型类型或方法 'T' 中的类型参数 'BaseController<T>' 。没有隐式引用

c# - 使单元格不可编辑

c# - 我是否需要 Dispose() 或 Close() 一个 EventWaitHandle?

c# - 为什么当我切换语义缩放时,它没有导航到该部分?