方法的重写与隐藏
我们先来看一个例子
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
class Program
{
static void Main(string[] args)
{
BaseClass baseClass = new DerivedClass();
Console.WriteLine(baseClass.GetString());
//DerivedClass driverclass = new DerivedClass();
//Console.WriteLine(driverclass.GetString());
Console.ReadLine();
}
}
public class BaseClass
{
public virtual string GetString()
{
return "这是基类的GetString()方法。";
}
}
public class DerivedClass : BaseClass
{
public override string GetString()
{
return "这是继承类的GetString()方法。";
}
}
{
static void Main(string[] args)
{
BaseClass baseClass = new DerivedClass();
Console.WriteLine(baseClass.GetString());
//DerivedClass driverclass = new DerivedClass();
//Console.WriteLine(driverclass.GetString());
Console.ReadLine();
}
}
public class BaseClass
{
public virtual string GetString()
{
return "这是基类的GetString()方法。";
}
}
public class DerivedClass : BaseClass
{
public override string GetString()
{
return "这是继承类的GetString()方法。";
}
}
输出结果是:这是继承类的GetString()方法。
之所以出现这个结果,是因为GetString()方法被继承类重写。那如果我们把 继承类的GetString()方法的修饰符从 override 改为 new ,会输出什么样的结果呢?
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
class Program
{
static void Main(string[] args)
{
BaseClass baseClass = new DerivedClass();
Console.WriteLine(baseClass.GetString());
//DerivedClass driverclass = new DerivedClass();
//Console.WriteLine(driverclass.GetString());
Console.ReadLine();
}
}
public class BaseClass
{
public virtual string GetString()
{
return "这是基类的GetString()方法。";
}
}
public class DerivedClass : BaseClass
{
public new string GetString()
{
return "这是继承类的GetString()方法。";
}
}
{
static void Main(string[] args)
{
BaseClass baseClass = new DerivedClass();
Console.WriteLine(baseClass.GetString());
//DerivedClass driverclass = new DerivedClass();
//Console.WriteLine(driverclass.GetString());
Console.ReadLine();
}
}
public class BaseClass
{
public virtual string GetString()
{
return "这是基类的GetString()方法。";
}
}
public class DerivedClass : BaseClass
{
public new string GetString()
{
return "这是继承类的GetString()方法。";
}
}
这时输出结果为:这是基类的GetString()方法。
看,这时调用的是基类的方法。继承类隐藏了基类中的GetString方法
作者:陈 锋
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。