方法 new override virtual
摘 : http://hacker.cnblogs.com/archive/2004/08/10/31774.aspx
對virtual的說明是對的:(它一般用在基類中,子類中用override)
1.無virtual時,編譯期就確定方法的類型了。也即:無法實(shí)現(xiàn)多態(tài)了。
2.有vitual時,方法在運(yùn)行時確定類型。可以實(shí)現(xiàn)多態(tài),只要子類override基類的vitual方法。(也就是樓主的第2點(diǎn))。
實(shí)現(xiàn)java 動態(tài)調(diào)用
另外取個方法 與原來無關(guān).
對于new沒有說清楚:
new與virtual并沒有必然的聯(lián)系。從字面上看,new聲明的方法是一個“新”方法,與基類完全沒有關(guān)系(雖然不幸與基類的某個方法同名同參)。也即:通過向上轉(zhuǎn)型(如:基類 引用名=new 子類())得到的引用將無法看到子類中new出來的方法。所以會出現(xiàn)樓主第3點(diǎn)中的結(jié)果。
using System;
public class ClassFather
{
public string s1;
// virtual public void VirFun()
public void VirFun()
{ Console.WriteLine( "base classfather virFun:"+ s1 );}
}
public class ClassBoy : ClassFather
{
public new void VirFun()
{ base.VirFun();}
}
public class ClassGirl : ClassFather
{
public new void VirFun()
{
base.VirFun();
Console.WriteLine( s1 );
}
}
public class Test
{
public static void Main()
{
ClassFather a = new ClassFather();
a.s1 = "father";
a.VirFun();
ClassFather b = new ClassBoy();
b.s1 = "boy";
b.VirFun();
ClassFather c = new ClassGirl();
c.s1 = "girl";
c.VirFun();
}
}
public class ClassFather
{
public string s1;
// virtual public void VirFun()
public void VirFun()
{ Console.WriteLine( "base classfather virFun:"+ s1 );}
}
public class ClassBoy : ClassFather
{
public new void VirFun()
{ base.VirFun();}
}
public class ClassGirl : ClassFather
{
public new void VirFun()
{
base.VirFun();
Console.WriteLine( s1 );
}
}
public class Test
{
public static void Main()
{
ClassFather a = new ClassFather();
a.s1 = "father";
a.VirFun();
ClassFather b = new ClassBoy();
b.s1 = "boy";
b.VirFun();
ClassFather c = new ClassGirl();
c.s1 = "girl";
c.VirFun();
}
}















































































posted on 2008-08-29 08:26 小高 閱讀(236) 評論(0) 編輯 收藏 所屬分類: DotNet