检查 ReadOnlyMemory<char> 是否包含在 C# 中的哈希集中的有效方法

问题描述 投票:0回答:1

我一直在寻找一些有效且精确的方法来检查 C# 中的

ReadOnlyMemory<char>
是否包含在 ReadOnlyMemory 或任何其他集合的
Hashset
中。

我看到了一些转换为字符串的建议,但我非常希望避免它以提高内存效率。我发现的唯一其他方法是编写自定义

IEqualityComparer
,但我也想知道是否有人发现了更好的解决方案。

c# asp.net hashset
1个回答
0
投票

由于(至少在 .net8 中)它实现了 IEquatable 并具有 GetHashCode,它使用真实数据而不是内存地址,因此它应该开箱即用。


public bool Equals(ReadOnlyMemory<T> other)
{
     return
         _object == other._object &&
         _index == other._index &&
         _length == other._length;
}

public override int GetHashCode()
{
    // We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
    // code is based on object identity and referential equality, not deep equality (as common with string).
    return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.