【问题标题】:How to use an object's identity as key for Dictionary<K,V>如何使用对象的身份作为 Dictionary<K,V> 的键
【发布时间】:2012-01-20 19:25:24
【问题描述】:

是否可以将对象用作Dictonary&lt;object, ...&gt; 的键,这样字典才会仅在对象相同时将它们视为相等?

例如,在下面的代码中,我希望第 2 行返回 11 而不是 12:

Dictionary<object, int> dict = new Dictionary<object, int>();
object a = new Uri("http://www.google.com");
object b = new Uri("http://www.google.com");

dict[a] = 11;
dict[b] = 12;

Console.WriteLine(a == b);  // Line 1. Returns False, because a and b are different objects.
Console.WriteLine(dict[a]); // Line 2. Returns 12
Console.WriteLine(dict[b]); // Line 3. Returns 12

当前 Dictionary 实现在键上使用object.Equals()object.GetHashCode();但我正在寻找一种不同类型的字典,它使用对象的 identity 作为键(而不是对象的值)。 .NET 中是否有这样的字典,还是我必须从头开始实现它?

【问题讨论】:

  • “对象标识”在 .NET 中不是一个术语 - 实际上您的语言是相反的:ab 是不同的对象(具有不同的内存地址)但具有相同的 value - 你的描述暗示你确实想使用键的值,而不是它们的内存地址。

标签: c# .net


【解决方案1】:

您不需要构建自己的字典 - 您需要构建自己的 IEqualityComparer&lt;T&gt; 实现,它使用身份来进行哈希和相等。我认为框架中不存在这样的东西,但由于RuntimeHelpers.GetHashCode,它很容易构建。

public sealed class IdentityEqualityComparer<T> : IEqualityComparer<T>
    where T : class
{
    public int GetHashCode(T value)
    {
        return RuntimeHelpers.GetHashCode(value);
    }

    public bool Equals(T left, T right)
    {
        return left == right; // Reference identity comparison
    }
}

我已将T 限制为引用类型,以便您在字典中得到objects;如果你将它用于值类型,你可能会得到一些奇怪的结果。 (我不知道这会如何工作;我怀疑不会。)

有了这些,剩下的就很容易了。例如:

Dictionary<string, int> identityDictionary =
    new Dictionary<string, int>(new IdentityEqualityComparer<string>());

【讨论】:

  • 我最近构建了一个类似的构造,尽管我在 Equals 方法中使用了 object.ReferenceEquals,因为我想检查引用是否相等,即使 == 运算符已重载(然后可能会调用重写的 Equals对象的方法)。
  • @JamesShuttler:即使 == 在执行时被 actual T 重载,这里的约束也不会强制 T 成为重载,所以这 是引用相等。 (用字符串试试,例如...)
【解决方案2】:

当然其他答案是完全正确的,但我写了自己的版本来满足我的需要:

/// <summary>
/// An equality comparer that compares objects for reference equality.
/// </summary>
/// <typeparam name="T">The type of objects to compare.</typeparam>
public sealed class ReferenceEqualityComparer<T> : IEqualityComparer<T>
    where T : class
{
    #region Predefined
    private static readonly ReferenceEqualityComparer<T> instance
        = new ReferenceEqualityComparer<T>();
    /// <summary>
    /// Gets the default instance of the
    /// <see cref="ReferenceEqualityComparer{T}"/> class.
    /// </summary>
    /// <value>A <see cref="ReferenceEqualityComparer<T>"/> instance.</value>
    public static ReferenceEqualityComparer<T> Instance
    {
        get { return instance; }
    }
    #endregion

    /// <inheritdoc />
    public bool Equals(T left, T right)
    {
        return Object.ReferenceEquals(left, right);
    }

    /// <inheritdoc />
    public int GetHashCode(T value)
    {
        return RuntimeHelpers.GetHashCode(value);
    }
}

设计原理:

  • 班级是sealed

    如果课程不是为扩展而设计的,我将通过密封它来避免所有这些费用。
    Eric Lippert

    我认识很多人(包括我自己)认为类确实应该默认密封。
    Jon Skeet

  • 有一个Instance static read-only property 可以公开此类的单个实例。
  • 它使用Object.ReferenceEquals() 而不是==,因为ReferenceEquals 更明确。
  • 它使用RuntimeHelpers.GetHashCode(),因为我不想使用可能被覆盖的对象GetHashCode,这可能与ReferenceEquals 的行为不匹配。这也避免了空检查。
  • 它有文档。

【讨论】:

  • 我通常发现拥有一个公共课程而不是一个非密封课程更像是一种“犯罪”。很少有类最终成为所需公共 API 的一部分:除非它需要公开,否则将其保留在内部(对项目而言)!
【解决方案3】:

使用你自己的相等比较器

public class ObjectIdentityEqualityComparer : IEqualityComparer<object>
{
    public int GetHashCode(object o)
    {
        return o.GetHashCode();
    }

    public bool Equals(object o1, object o2)
    {
        return object.ReferenceEquals(o1, o2);
    }
}

请注意,GetHashCode 可以被覆盖,但关键检查是使用 Equals 进行的。

【讨论】:

  • 我认为你的意思是覆盖,但即便如此,为了提高效率,最好使用RuntimeHelpers.GetHashCode。 (顺便说一句,有什么理由对其中一半使用显式实现,而对另一半不使用?)
  • 我使用了微软的MS.Internal.ComponentModel.ReferenceEqualityComparer 实现。我也想知道为什么他们混合了隐式/显式实现。我将代码更改为更加一致。
【解决方案4】:

从 5.0 开始,ReferenceEqualityComparer 现在随运行时一起提供。

【讨论】:

    【解决方案5】:
    猜你喜欢
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多