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(); 基类方法的实现就被调用了。这种行为不同于改写方法,后者保证大部分派生方法获得调用。