字典允许我插入重复的键

Rag*_*ock 2 c# dictionary

我已经创建了一些类,因此我可以使用一对字典作为键

public class RouteKey
{
    public Equip Equipment { get; set; }
    public Destiny Destiny { get; set; }

    public RouteKey() { }
    public RouteKey(Equip Equipment, Destiny Destiny) {
        this.Equipment = Equipment;
        this.Destiny = Destiny;
    }
}

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

    if (this.GetType() != obj.GetType()) return false;

    RouteKey rk = (RouteKey)obj;

    // use this pattern to compare reference members
    if (!Object.Equals(Equipment, rk.Equipment)) return false;

    // use this pattern to compare value members
    if (!Destiny.Equals(rk.Destiny)) return false;

    return true;        
}

public class RouteValue
{
    public string Endpoint { get; set; }
    public bool Enabled { get; set; }

    public RouteValue() { }
    public RouteValue(string Endpoint, bool Enabled) {
        this.Endpoint = Endpoint;
        this.Enabled = Enabled;
    }
}

public Dictionary<RouteKey, RouteValue> Routes;
Run Code Online (Sandbox Code Playgroud)

我的问题是我能够毫无错误地运行此代码...

RouteKey rk1 = new RouteKey(Equip.SpaceShip, Destiny.sun);
RouteKey rk2 = new RouteKey(Equip.SpaceShip, Destiny.sun);
RouteKey rk3 = new RouteKey(Equip.Boat, Destiny.hell);

RouteValue rv1 = new RouteValue("rv1", true);
RouteValue rv2 = new RouteValue("rv2", false);
RouteValue rv3 = new RouteValue("rv3", true);

Routes.Add(rk1, rv1);
Routes.Add(rk3, rv3);
Routes.Add(rk2, rv2);
Run Code Online (Sandbox Code Playgroud)

我已经尝试将equals方法添加到RouteKey类,但在调试中我可以看到代码永远不会通过该方法.

如果要使字典按预期运行,我该怎么办?

das*_*ght 7

RouteKey需要以GetHashCode()相同RouteKey实例的哈希码也相等的方式覆盖该方法(但不一定是相反的方式).