【问题标题】:Is there a way to retrieve a Dictionary key using an equivalent key?有没有办法使用等效键检索字典键?
【发布时间】:2014-05-29 23:53:08
【问题描述】:

我使用自定义类作为 Dictionary(TKey, TValue) 的键。该类覆盖GetHashCode和Equals等。

我想做的是添加一个键/值对;稍后,生成一个与第一个键等效的新键(相同的哈希码,Equals 返回 true),并使用此等效键,不仅检索值,还检索到 原始首次添加到字典中的键。

例子:

var keyA = new KeyClass("abc123");
var keyB = new KeyClass("abc123"); // same as far as dictionary is concerned

var dict = new Dictionary<KeyClass, Object>();

dict.Add(keyA, value);

现在如何使用 keyB 从字典中获取对 keyA 的引用?

看起来这应该很容易在不枚举 Keys 集合的情况下完成,因为 Dictionary 已经对这些键进行了哈希处理,但我找不到 Dictionary 类中内置的任何内容。我错过了什么吗?就目前而言,我要么必须使用双向字典并进行反向查找,要么(在这种情况下我的偏好)“增强”我用于值的类,以便它们存储对原始键的引用。

【问题讨论】:

  • "该类覆盖 GetHashCode 和 Equals 等" - 可能出现什么问题? ;)
  • 我不确定你想要达到什么目的?为什么枚举 Keys 还不够?
  • @MitchWheat 在类中实现IEquatable 时需要覆盖这些方法。 msdn.microsoft.com/en-us/library/ms131190(v=vs.110).aspx
  • @Smeegs:是的,我知道!
  • 我的意思是 10 次中有 9 次,人们都弄错了。

标签: c# .net


【解决方案1】:

嗯,@AD.Net 是合适的答案,这在覆盖 GetHashCode()Equals() 时大部分是正确的

public class KeyClass 
{

   public readonly string key;

   public KeyClass(string key)
   {
      this.key = key;
   }

   public override bool Equals(object other)
   {
       if (other == null)
         return false;

       // Casting object other to type KeyClass
       KeyClass obj = other as KeyClass;
       if (obj == null)
         return false;

        return this.key == other.key;
   }

   public override int GetHashCode()
   {
        return this.key.GetHashCode();
   }
}

【讨论】:

  • 如果不能将other 转换为KeyClass,显式转换是否会抛出异常?也许KeyClass obj = other as KeyClass; 在这里更合适。 (当然,事后检查null 是必须的)。
  • @Corak 是的,我会尽可能快地回答,非常抱歉。如果KeyClass obj = (KeyClass) obj 会提高InvalidCastException 我知道
  • 我不确定你想在这里告诉我什么 - 我不是在尝试设计 KeyClass,我是在尝试获取对最初添加到的 KeyClass 实例的引用字典。
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 2020-03-24
  • 2019-01-17
  • 2016-07-25
  • 1970-01-01
相关资源
最近更新 更多