【发布时间】:2010-02-22 18:18:02
【问题描述】:
我对 new 关键字有些困惑,当我使用 virtual 和 override 时一切正常,但与 new 有点不同(我想我遗漏了一些东西)
class A
{
public virtual void Test()
{
Console.WriteLine("I am in A");
}
}
class B:A
{
public override void Test()
{
Console.WriteLine("I am in B");
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
b.Test(); //I am in B
A a = new B();
Console.WriteLine(a.GetType()); // Type-B
a.Test(); //I am in B
Console.ReadKey();
}
}
}
现在有了新的
class A
{
public void Test()
{
Console.WriteLine("I am in A");
}
}
class B:A
{
public new void Test()
{
Console.WriteLine("I am in B");
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
b.Test(); //I am in B
A a = new B();
Console.WriteLine(a.GetType()); //B
a.Test(); // I am in A ? why?
Console.ReadKey();
}
}
根据 MSDN 使用 new 关键字时,将调用新的类成员而不是已替换的基类成员。这些基类成员称为隐藏成员,GetType() 也将类型显示为 B。 所以我哪里出错了,这似乎是一个愚蠢的错误:-)
【问题讨论】:
标签: c# new-operator shadowing