在虚拟方法上使用new的重点是什么?

时间:2017-02-28 04:35:07

标签: c# polymorphism method-overriding virtual-method sealed

在下面的示例中,为什么带有math关键字的new方法仍然可以正常运行,即使它所在的类派生自重写方法被密封的类?是不是有一个方法sealed确保它不能被继承或虚拟?

public class Program
{
    public static void Main(string[] args)
    {
        Utility u = new Utility();
        Entity e = new Entity();
        Last n = new Last();

        Console.WriteLine(u.math(2,3));
        Console.WriteLine(e.math(99,9));
        Console.WriteLine(n.math(4,4)); //Why doesn't this line give a compiler error?
    }
}

public class Utility
{
    public virtual int math(int x, int y)
    {
        return x + y;
    }
}

public class Entity : Utility
{
    public sealed override int math(int x, int y)
    {
        return x / y;
    }
}

public class Last : Entity
{
    public new int math(int x, int y)
    {
        return x * y + 100;
    }
}

输出:

5

11

116

0 个答案:

没有答案