Sky*_*kyN 18 .net c# dictionary
namespace Dic
{
public class Key
{
string name;
public Key(string n) { name = n; }
}
class Program
{
static string Test()
{
Key a = new Key("A");
Key b = new Key("A");
System.Collections.Generic.Dictionary<Key, int> d = new System.Collections.Generic.Dictionary<Key, int>();
d.Add(a, 1);
return d.ContainsKey(b).ToString();
}
static void Main(string[] args)
{
System.Console.WriteLine(Test());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该改变什么才能成真?
Ita*_*aro 36
你想要真实 - 但a和b是不同的对象.
您需要在类Key上覆盖GetHashCode和Equals
public class Key
{
string name;
public Key(string n) { name = n; }
public override int GetHashCode()
{
if (name == null) return 0;
return name.GetHashCode();
}
public override bool Equals(object obj)
{
Key other = obj as key;
return other != null && other.name == this.name;
}
}
Run Code Online (Sandbox Code Playgroud)
如果你重写Key.GetHashCode和Key.Equals,它可能会有所帮助.
在Key:
public override bool Equals(object obj)
{
var k = obj as Key;
if (k != null)
{
return this.name == k.name;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return this.name.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
覆盖类的 GetHashCode 和 Equals 方法使其在字典中正常工作并不是一个很好的方法。字典的行为方式应该是字典的实现细节,而不是用作键的任何类。当您想在具有不同行为的不同词典中使用该类时,您会遇到麻烦。或者,如果您无权访问类源代码。
更好的捕鼠器是为字典提供自己的比较器。例如:
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
var d = new Dictionary<Key, int>(new MyComparer());
d.Add(new Key("A"), 1);
Console.WriteLine(d.ContainsKey(new Key("a")));
Console.ReadLine();
}
private class MyComparer : IEqualityComparer<Key> {
public bool Equals(Key x, Key y) {
return string.Compare(x.Name, y.Name, true) == 0;
}
public int GetHashCode(Key obj) {
return obj.Name.ToUpper().GetHashCode();
}
}
public class Key {
public string Name { get; set; }
public Key(string name) { Name = name; }
}
}
Run Code Online (Sandbox Code Playgroud)
如果你没有能力像其他人提到的那样覆盖相等的运算符/ Equals/GetHashCode(如你所知,你不控制对象的源代码),你可以IEqualityComparer<Key>在字典的构造函数中提供一个实现来执行你的相等检查.
class KeyComparer : IEqualityComparer<Key>
{
public bool Equals(Key x, Key y)
{
return x.Name == y.Name;
}
public int GetHashCode(Key obj)
{
return obj.Name.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
就目前而言,您的Key是一个引用对象,因此除非您告诉世界(或字典),否则仅在引用时确定相等性.