繁体   English   中英

使用“external”GetHashCode和Equals for Dictionary

[英]Use “external” GetHashCode and Equals for Dictionary

我想在Dictionary中使用一个类作为键,它不会覆盖Equals和GetHashCode。 这是一个来自外部库的类,我不想修改它。

所以我想知道我是否可以为一个字典使用自定义的“GetHashCode”/“Equals”实现? 我想知道是否有可能像C ++ std :: maps这样的东西

template < class Key,                      // map::key_type
           class T,                        // map::mapped_type
           class Compare = less<T>,        // map::key_compare
           class Alloc = allocator<T> >    // map::allocator_type
           > class map;

其中Compare可用于定义自定义比较。

我不想从类派生,因为对象是使用现有类在外部创建的。

我可以创建一个包含原始类的类,但这会更改对Dictionary的访问。

谢谢你的想法!

当然 - 您可以实现IEqualityComparer<T>并将其传递到Dictionary<,>构造函数中 这正是构造函数的目的:)

例如:

public FooByNameEqualityComparer : IEqualityComparer<Foo>
{
    public int GetHashCode(Foo foo)
    {
        return foo.Name.GetHashCode();
    }

    public bool Equals(Foo x, Foo y)
    {
        return x.Name == y.Name;
    }
}

...

Dictionary<Foo, int> map = new Dictionary<Foo, int>(new FooByNameComparer());

您可以将自定义IEqualityComparer<TKey>传递给Dictionary<TKey,TValue>的构造函数。 相等比较器必须实现EqualGetHashCode

var dict = new Dictionary<MyKey,MyValue>(new MyKeyEqualityComparer());

您可以使用Dictionary Constructor(Int32,IEqualityComparer)

public Dictionary(
    int capacity,
    IEqualityComparer<TKey> comparer
)

哪里

comparer是:

比较时使用的实现

在实践中

  • 您定义实现该接口的类型
  • 其传递给该构造函数, 使得类的方法被useed用于字典的键的平等鉴定。

似乎你想要什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM