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

慕工程0101907
TA貢獻1887條經(jīng)驗 獲得超5個贊
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,如果使用覆蓋,則會打印true。

汪汪一只貓
TA貢獻1898條經(jīng)驗 獲得超8個贊
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 關注
- 534 瀏覽
添加回答
舉報
0/150
提交
取消