c# - 对象作为字典中的键

标签 c# asp.net dictionary c#-3.0 c#-2.0

我有这门课:

class A {
    string name;
    string code;
}

例子:

A1: name="blabla", code="kuku"
A2: name="blabla", code=null
A3: name=null, code="kuku"

Dictionary<A, string> d=new Dictionary<A, string>();

d[A1]="aaa";
d[A2]="bbb"
results: d[A1]="bbb";

d[A1]="aaa";
d[A3]="bbb"
results: d[A1]="bbb";

d[A2]="aaa";
d[A3]="bbb"
results: d[A2]="aaa"; d[A3]="bbb";

有没有办法将 A 类实现为字典的键?

最佳答案

你不能。

Equals/GetHashCode 实现必须形成[等价关系] - 它们必须满足以下属性:

  • 一个==一个。 (反身性)
  • 如果 a == b 则 b == a。 (对称)
  • 如果 a == b 且 b == c 则 a == c。 (传递性)

你的定义是不可传递的; (a, b) == (b, c)(b, c) == (c, d)(a, b) != (c, d)

关于c# - 对象作为字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709448/

相关文章:

c# - 服务器上的 HangFire 重复作业失败,并出现 Autofac.Core.Registration.ComponentNotRegisteredException 或无参数异常

c# - 为 T-SQL 字符串文字正确的字符串转义

c# - 如何使用 Ocelot API 网关重新路由支持 Kubernetes 就绪/事件探测?

javascript - SignalR 更改中心订阅

c# - Distinct 子句导致类型错误

python - MRJob MR 分配给Dictionary 而不是Yield?

vb.net - 在VB中将列表转换为字典

c# - 项目引用问题

ASP.net:更改默认的 Web 控件属性

python - 将字典列表转换为字典