1: using System; 2: 3: class Triangle 4: { 5: public virtual double ComputeArea(int a, int b, int c) 6: { 7: // Heronian formula 8: double s = (a + b + c) / 2.0; 9: double dArea = Math.Sqrt(s*(s-a)*(s-b)*(s-c)); 10: return dArea; 11: } 12: } 13: 14: class RightAngledTriangle:Triangle 15: { 16: public override double ComputeArea(int a, int b, int c) 17: { 18: double dArea = a*b/2.0; 19: return dArea; 20: } 21: } 22: 23: class TriangleTestApp 24: { 25: public static void Main() 26: { 27: Triangle tri = new Triangle(); 28: Console.WriteLine(tri.ComputeArea(2, 5, 6)); 29: 30: RightAngledTriangle rat = new RightAngledTriangle(); 31: Console.WriteLine(rat.ComputeArea(3, 4, 5)); 32: } 33: }
1: class BaseClass 2: { 3: public void TestMethod() 4: { 5: Console.WriteLine("BaseClass::TestMethod"); 6: } 7: } 8: 9: class DerivedClass:BaseClass 10: { 11: public void TestMethod() 12: { 13: Console.WriteLine("DerivedClass::TestMethod"); 14: } 15: }
在優秀的編程語言中,你現在會遇到一個真正的大麻煩。但是,C#會給你提出警告: hiding2.cs(13,14): warning CS0114: 'DerivedClass.TestMethod()' hides inherited member 'BaseClass.TestMethod ()'. To make the current method override that implementation, add the override keyWord. Otherwise add the new keyword. (hiding2.cs(13,14):警告 CS0114:'DerivedClass.TestMethod()' 屏蔽了所繼承的成員'BaseClass.TestMethod()'。要 想使當前方法改寫原來的實現,加上 override關鍵字。否則加上新的關鍵字。) 具有了修飾符new,你就可以告訴編譯器,不必重寫派生類或改變使用到派生類的代碼,你的方法就能屏蔽新加入的基類方 法。清單5.8 顯示如何在例子中運用new修飾符。
清單 5.8 屏蔽基類方法
1: class BaseClass 2: { 3: public void TestMethod() 4: { 5: Console.WriteLine("BaseClass::TestMethod"); 6: } 7: } 8: 9: class DerivedClass:BaseClass 10: { 11: new public void TestMethod() 12: { 13: Console.WriteLine("DerivedClass::TestMethod"); 14: } 15: }
使用了附加的new修飾符,編譯器就知道你重定義了基類的方法,它應該屏蔽基類方法。但是,如果你按以下方式編寫: DerivedClass test = new DerivedClass(); ((BaseClass)test).TestMethod(); 基類方法的實現就被調用了。這種行為不同于改寫方法,后者保證大部分派生方法獲得調用。