需要说明:虚拟,覆盖和基础

时间:2014-05-17 09:33:17

标签: c# override virtual base

为什么O.W2()中的“,Second ID:”字符串没有打印出来?我知道D2属性是空的。

using System;

public class O
{
    public string F { get; set; }
    public string L { get; set; }
    public string D { get; set; }

    public virtual string W()
    {
        return this.W2();
    }

    public virtual string W2()
    {
        return string.Format("First Name : {0}, Last name: {1}, ID: {2}", F, L, D);
    }
}

public class S : O
{
    public string D2 { get; set; }

    public override string W()
    {
        return base.W2();
    }

    public override string W2()
    {
        return base.W2() + string.Format(", Second ID: {0}", this.D2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        O o = new S();

        o.D = "12345678";
        o.F = "John";
        o.L = "Jones";

        Console.WriteLine(o.W());

        // Output: First Name : John, Last name: Jones, ID: 12345678
    }
}

2 个答案:

答案 0 :(得分:2)

因为您致电override W(),而base.W2()又调用了base.W2()。在类中,public override string W() { // directly calls W2() from the base class, ignores the override return base.W2(); } 是静态地(在编译时)确定为基类中的那个:

base

如果您想要针对此方案使用多态,则应省略W2()并只需致电public override string W() { // goes to the override return W2(); }

{{1}}

答案 1 :(得分:0)

永远不会调用S对象中的函数W2()!!

当你在S对象中调用W()时,你使它调用了基础W2()

试试这样:

public override string W()
{
    String x = base.W2();
    x = x + this.W2();
    return x;
}