昨天终于对new关键字对类成员的阻断作用有了比较清晰的认识,“对类成员的阻断”是王涛大哥在其作品《你必须知道的.NET》的说法,昨天在园里看到一位前辈戏称之为“封印咒术”,我感觉这个说法很贴切。比如Sons类继承自Fathers类,在Sons中对Fathers的虚方法DoVirtualWork()实现了封印,则以后继承自Sons的类就无法继承Fathers的DoVirtualWork()方法。代码如下:
Code
public class Fathers
{
public void DoWork()
{
Console.WriteLine("Father.DoWork()");
}
public virtual void DoVirtualWork()
{
Console.WriteLine("Father.DoVirtualWork()");
}
}
public class Sons : Fathers
{
public new void DoVirtualWork()
{
//base.DoVirtualWork();
Console.WriteLine("Son.DoVirtualWork()");
}
}
public class Grandsons : Sons
{
}
public class Sonson : Sons
{
}
class Program
{
static void Main(string[] args)
{
//调用Sons.DoVirtualWork()
Sons person1 = new Grandsons();
person1.DoVirtualWork();
//调用Sons.DoVirtualWork()
Sons person2 = new Sons();
person2.DoVirtualWork();
//调用Fathers.DoVirtualWork()
Fathers person = new Grandsons();
person.DoVirtualWork();
//调用Fathers.DoVirtualWork()
Fathers person3 = new Sonson();
person3.DoVirtualWork();
//调用Sons.DoVirtualWork()
Sonson person4 = new Sonson();
person4.DoVirtualWork();
Console.Read();
}
}
public class Fathers
{
public void DoWork()
{
Console.WriteLine("Father.DoWork()");
}
public virtual void DoVirtualWork()
{
Console.WriteLine("Father.DoVirtualWork()");
}
}
public class Sons : Fathers
{
public new void DoVirtualWork()
{
//base.DoVirtualWork();
Console.WriteLine("Son.DoVirtualWork()");
}
}
public class Grandsons : Sons
{
}
public class Sonson : Sons
{
}
class Program
{
static void Main(string[] args)
{
//调用Sons.DoVirtualWork()
Sons person1 = new Grandsons();
person1.DoVirtualWork();
//调用Sons.DoVirtualWork()
Sons person2 = new Sons();
person2.DoVirtualWork();
//调用Fathers.DoVirtualWork()
Fathers person = new Grandsons();
person.DoVirtualWork();
//调用Fathers.DoVirtualWork()
Fathers person3 = new Sonson();
person3.DoVirtualWork();
//调用Sons.DoVirtualWork()
Sonson person4 = new Sonson();
person4.DoVirtualWork();
Console.Read();
}
}
运行结果:
Son.DoVirtualWork()
Son.DoVirtualWork()
Father.DoVirtualWork()
Father.DoVirtualWork()
Son.DoVirtualWork()
所以,在类的设计中尽可能不用new阻断类成员。