c# - Explanation needed: virtual, override and base -
why doesn't ", second id: " string in o.w2() printed out? know d2 property empty.
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 } }
because called override w()
in turn calls base.w2()
. inside class, base.w2()
determined statically (at compile time) 1 in base class:
public override string w() { // directly calls w2() base class, ignores override return base.w2(); }
if want polymorphism scenario, should omit base
, call w2()
:
public override string w() { // goes override return w2(); }
Comments
Post a Comment