我有一些困惑與新的關鍵字,東西很好地工作,當我使用虛擬和覆蓋,但隨着新的(我想我失去了一些東西)怎樣新的關鍵字工作在派生類
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當使用新的關鍵字,新的類成員被調用,而不是已被替換的基類成員。這些基類成員稱爲隱藏成員,也對GetType()是類型B. 那麼,我錯了,看來它是一個愚蠢的錯誤:-)
這意味着這是編譯時間與運行時間..我明白了你的觀點,thnx。 – Wondering