先看下面这段代码的输出:
class ClassA
{
public virtual void WriteString()
{
Console.WriteLine("ClassA类virtual WriteString");
}
public void Write()
{
Console.WriteLine("ClassA类void Write");
}
}
class ClassB : ClassA
{
public override void WriteString()
{
Console.WriteLine("ClassB类override void WriteString");
}
public new void Write()
{
Console.WriteLine("ClassB类new void Write");
}
}
class WatinConsoleExample
{
[STAThread]
static void Main(string[] args)
{
ClassB b = new ClassB();
ClassA a = (ClassA)b; //转换为其类
a.WriteString(); //ClassB中用override实现,输出为: ClassB类override void WriteString
a.Write(); // ClassB中用new实现,输出为: ClassA类void Write
Console.ReadLine();
}
}
{
public virtual void WriteString()
{
Console.WriteLine("ClassA类virtual WriteString");
}
public void Write()
{
Console.WriteLine("ClassA类void Write");
}
}
class ClassB : ClassA
{
public override void WriteString()
{
Console.WriteLine("ClassB类override void WriteString");
}
public new void Write()
{
Console.WriteLine("ClassB类new void Write");
}
}
class WatinConsoleExample
{
[STAThread]
static void Main(string[] args)
{
ClassB b = new ClassB();
ClassA a = (ClassA)b; //转换为其类
a.WriteString(); //ClassB中用override实现,输出为: ClassB类override void WriteString
a.Write(); // ClassB中用new实现,输出为: ClassA类void Write
Console.ReadLine();
}
}
上面这段代码的输出结果为:
ClassB类override void WriteString
ClassA类void Write
由此得出结论:
1.派生类中用new实现基类的同名方法,把派生类强制转换为基类型时,将调用基类中的实现;
2.相反,派生类中用override 实现基类的virtual 同名方法,把派生类强制转换为基类型时,仍将调用派生类自己的实现。
转自star163的博客,原文地址http://www.cnblogs.com/finejob/articles/970957.html