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());
}
}
}
我应该做哪些更改才能得到 true?
Key
确实如此简单,您可以将其定义为一个struct
。 - Tobyint
类型;) - Mark SeemannValueType.Equals
默认通过检查每个结构体的字段来比较它们。然而,它使用反射来实现,因此性能受到影响。在我的看法中,当意图将类型用作字典中的键时,覆盖Equals
和GetHashCode
通常是更好的方法。 - Dan Tao