简体   繁体   中英

Inheritance calling wrong Equals() method

I have a question about overriding method Equals .

public class Asset
{
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        Asset oAss = (Asset)obj;
        return Name == oAss.Name;
    }
}

public class Mortage : Asset
{
    public int Amount { get; set; }

    public override bool Equals(object obj)
    {
        Mortage oMor = (Mortage)obj;
        return this.Name == oMor.Name && this.Amount == oMor.Amount;
    }
}

    static void Main(string[] args)
    {
        Mortage m1 = new Mortage();
        Mortage m2 = new Mortage();

        m1.Name = "House";
        m1.Amount = 2000;

        m2.Name = "Castle";
        m2.Amount = 200000;


        Asset a1 = m1;
        Asset a2 = m2;


        m1.Equals(m2);
        a1.Equals(a2);

    }

Why when I call the method a1.Equals(a2) this is the Mortage.Equals() which is called and not the Asset.Equals() ?

Because m1 and a1 are still the same instance of type Mortgage .

In this case the type system doesn't care what the variable type is, it uses the actual type to find the highest derived method that complies to the signature bool (object) , which is still Mortgage.Equals because it overrides the method from Asset . Marking the Mortgage.Equals method new would make that code call Asset.Equals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM