(C#)一道看似简单却很难答得完全正确的关于多态的问题
[csharp]/*关于virtual,overried,new在方法和属性上以this,base形式输出的问题
*问主程序的输出是什么
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
A a1 = new B();
a1.AM1();
B b1 = (B)a1;
b1.AM1();
Console.WriteLine();
A a2 = new B();
a2.AM2();
B b2 = (B)a2;
b2.AM2();
}
}
class A
{
public virtual int i { get; protected set; }
public A()
{
this.i = 9;
}
public virtual void AM1()
{
this.i = this.i + 10000;
Console.WriteLine("A.this.i="+ this.i);
}
public virtual void AM2()
{
this.i = this.i + 10000;
Console.WriteLine("A.this.i=" + this.i);
}
}
class B : A
{
public override int i { get; protected set; }
public B()
: base()
{
this.i = 5;
}
public override void AM1()
{
Console.WriteLine("B.this.i=" + this.i);
Console.WriteLine("B.base.i=" + base.i);
this.i = this.i + 100;
base.i = base.i + 1000;
Console.WriteLine("B.this.i=" + this.i);
Console.WriteLine("B.base.i=" + base.i);
}
public new void AM2()
{
Console.WriteLine("B.this.i=" + this.i);
Console.WriteLine("B.base.i=" + base.i);
this.i = this.i + 100;
base.i = base.i + 1000;
Console.WriteLine("B.this.i=" + this.i);
Console.WriteLine("B.base.i=" + base.i);
}
}
}
/* output
B.this.i=5
B.base.i=0
B.this.i=105
B.base.i=1000
B.this.i=105
B.base.i=1000
B.this.i=205
B.base.i=2000
A.this.i=10005
B.this.i=10005
B.base.i=0
B.this.i=10105
B.base.i=1000
*/
/*关于virtual,overried,new在方法和属性上以this,base形式输出的问题
*问主程序的输出是什么
*加了些log后
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
A a1 = new B();
a1.AM1();
B b1 = (B)a1;
b1.AM1();
Console.WriteLine();
A a2 = new B();
a2.AM2();
B b2 = (B)a2;
b2.AM2();
}
}
class A
{
private int tmp;
public virtual int i
{
get
{
Console.WriteLine(" A.i.get=" + this.tmp);
return this.tmp;
&nbs
补充:软件开发 , C# ,