我正在重构我的网络以使用 DotNetty。它有
IChannelId
,它使用 IComparable<IChannelId>
。
我有一本
IChannelId
的字典,其值为 IChannel
。我猜这是存储和检索频道的常见做法。
如何在查询时考虑到
IComparable
?以前我使用过 GUID 字符串。
这是我的新方法,但找不到频道。
public INetworkClient? TryGetClientByChannelId(IChannelId channelId)
{
return _clients.GetValueOrDefault(channelId);
}
我加个赞
public void AddClient(IChannelId channelId, INetworkClient client)
{
_clients[channelId] = client;
}
如果密钥未实现
IEquatable<T>
,或覆盖 Equals
和 GetHashCode
,那么您需要向字典提供自定义 IEqualityComparer<TKey>
。
public class ChannelIdComparer : IEqualityComparer<IChannelId>
{
public bool Equals(IChannelId x, IChannelId y)
{
if (ReferenceEquals(x, y)) return true;
if (x is null || y is null) return false;
return x.CompareTo(y) == 0; // Delegate to IComparable implementation
}
public int GetHashCode(IChannelId obj)
{
ArgumentNullException.ThrowIfNull(obj);
// TODO: Generate a hash code for the ID...
return 0;
}
}
Equals
方法很简单 - 您只需委托给IComparable<T>
实现即可。
GetHashCode
方法更难。您需要知道接口公开哪些属性,以及应使用其中哪些属性来评估相等性。
它不一定是完美的,但两个相等的实例必须返回相同的哈希码。
在这种情况下,我只是为所有实例返回
0
。这可行,但会将字典查找的效率降低到O(n)
,这不太理想。