例一:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VirtualMethod
{
class Program
{
static void Main(string[] args)
{
Base b1 = new Derived();
b1.Start();//输出什么?
b1.Stop();//输出什么?
b1.Turn();//输出什么?
}
}
public interface IVehicle
{
void Start();
void Stop();
void Turn();
}
public class Base : IVehicle
{
public void Start()
{
Console.WriteLine("a");
}
public void Stop()
{
Console.WriteLine("b");
}
public void Turn()
{
Console.WriteLine("c");
}
}
public class Derived : Base, IVehicle
{
void IVehicle.Start()
{
Console.WriteLine("d");
}
public void Stop()
{
Console.WriteLine("e");
}
public void Turn()
{
Console.WriteLine("f");
}
}
}
例二:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VirtualMethod
{
class Program
{
static void Main(string[] args)
{
ReallyDerived r1 = new ReallyDerived();
Derived r2 = r1;
Base r3 = r1;
ICommon r4 = r1;
r1.Doit();//输出什么?
r2.Doit();//输出什么?
r3.Doit();//输出什么?
r4.Doit();//输出什么?
}
}
public interface ICommon
{
void Doit();
}
public class Base : ICommon
{
void ICommon.Doit() { Console.WriteLine("a"); }
public virtual void Doit() { Console.WriteLine("b"); }
}
public class Derived : Base, ICommon
{
void ICommon.Doit() { Console.WriteLine("c"); }
public new virtual void Doit() { Console.WriteLine("d"); }
}
public class ReallyDerived : Derived
{
public override void Doit() { Console.WriteLine("e"); }
}
}
请问标记为“输出什么?”的各个语句输出什么?请给出原因或分析,谢谢了!
1.a,b,c 原因:都是Base类型;
2.e,e,b,c原因:是复写与就近原则