【问题标题】:Explanation needed: virtual, override and base需要解释:virtual、override 和 base
【发布时间】:2014-05-17 09:33:17
【问题描述】:

为什么没有打印出 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
    }
}

【问题讨论】:

    标签: c# overriding virtual base


    【解决方案1】:

    因为您调用了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(); 
    }
    

    【讨论】:

    • 这只是学校的一项任务,我不明白。 +(加号)让我很困惑,为什么它被忽略了?所以只有base.W2() 被输出,而不是+ string.Format(", Second ID: {0}", this.D2)
    • + 不会被忽略。问题是方法override string W2() 从未被调用过。只调用了base方法virtual string W2(),从override string W()调用,从void Main()调用。如果您将override string W() 更改为仅return W2()(而不是return base.W2()),我认为它会打印出您所期望的内容。
    • @Theodoros:您也许应该编辑您的答案以包含可以提供预期行为的代码?这将使答案更加清晰。
    • 哦,我的...当然,方法override string W2() 永远不会被调用。不知道我怎么没见过。谢谢!现在一切都清楚了。
    • @BinaryWorrier 当然!我刚做了。
    【解决方案2】:

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

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

    试试这样:

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

    【讨论】:

      猜你喜欢
      • 2011-09-03
      • 2010-11-21
      • 1970-01-01
      • 2013-07-20
      • 2010-10-19
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多