C#-關(guān)鍵字使用虛擬+重寫與新建在基類型中聲明方法之間有什么區(qū)別“virtual“然后使用override關(guān)鍵字,而不是簡(jiǎn)單地使用new“在子類型中聲明匹配方法時(shí)使用關(guān)鍵字?
3 回答

慕工程0101907
TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
public class Foo{ public bool DoSomething() { return false; }}public class Bar : Foo{ public new bool DoSomething() { return true; }}public class Test{ public static void Main () { Foo test = new Bar (); Console.WriteLine (test.DoSomething ()); }}
此打印為false,如果使用覆蓋,則會(huì)打印true。

汪汪一只貓
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
public class Foo{ public /*virtual*/ bool DoSomething() { return false; }}public class Bar : Foo{ public /*override or new*/ bool DoSomething() { return true; }}
Foo a = new Bar();a.DoSomething();
Bar
Foo
virtual
/override
new
- 3 回答
- 0 關(guān)注
- 538 瀏覽
添加回答
舉報(bào)
0/150
提交
取消