如果我想使用对象作为a的键Dictionary,我需要覆盖哪些方法以使它们以特定方式进行比较?
假设我有一个具有属性的类:
class Foo {
public string Name { get; set; }
public int FooID { get; set; }
// elided
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个:
Dictionary<Foo, List<Stuff>>
Run Code Online (Sandbox Code Playgroud)
我希望Foo具有相同对象的对象FooID被视为同一组.我需要在Foo课程中覆盖哪些方法?
总结一下:我想将Stuff对象分类为按Foo对象分组的列表.Stuff对象将有一个FooID将它们链接到他们的类别.
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)
我应该改变什么才能成真?