C# 中的重写与隐藏
csharpprogrammingserver side programming更新于 2025/8/13 14:37:17
重写
重写是指定义特定于子类类型的行为,这意味着子类可以根据其需求实现父类方法。
让我们看一个实现重写的抽象类的示例。 −
示例
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
阴影
阴影也称为方法隐藏。子类无需使用 override 关键字即可使用父类的方法进行阴影覆盖。子类拥有相同函数的自身版本。
使用 new 关键字执行阴影覆盖,并创建基类函数的自身版本。
让我们看一个例子 −
示例
using System;
using System.Collections.Generic;
class Demo {
public class Parent {
public string Display() {
return "Parent Class!";
}
}
public class Child : Parent {
public new string Display() {
return "Child Class!";
}
}
static void Main(String[] args) {
Child child = new Child();
Console.WriteLine(child.Display());
}
}

