需要 override
修饰符来扩展或修改继承方法、属性、索引器或事件的抽象或虚拟实现。
在以下示例中,该 Square
类必须提供重写的实现, GetArea
因为 GetArea
继承自抽象 Shape
类:
abstract class Shape
{
public abstract int GetArea();
}
class Square : Shape
{
private int _side;
public Square(int n) => _side = n;
// GetArea method is required to avoid a compile-time error.
public override int GetArea() => _side * _side;
static void Main()
{
var sq = new Square(12);
Console.WriteLine($"Area of the square = {sq.GetArea()}");
}
}
// Output: Area of the square = 144
方法 override
提供从基类继承的方法的新实现。 由 override
声明重写的方法称为重写基方法。 方法 override
必须具有与重写的基方法相同的签名。
override
方法支持协变返回类型。 具体而言,方法的 override
返回类型可以从相应基方法的返回类型派生。
不能替代非虚拟或静态方法。 重写的基方法必须是 virtual
, abstract
或 override
。
声明 override
无法更改方法的 virtual
可访问性。 方法和方法必须具有相同的访问级别修饰符。virtual
override
不能使用new
或static
virtual
修饰符修改方法override
。
重写属性声明必须指定与继承属性完全相同的访问修饰符、类型和名称。 只读重写属性支持协变返回类型。 重写的属性必须是 virtual
, abstract
或 override
。
有关如何使用 override
关键字的详细信息,请参阅 使用 Override 和 New Keywords 的版本控制 以及 了解何时使用 Override 和 New Keywords。 有关继承的信息,请参阅 “继承”。
示例:
此示例定义一 SalesEmployee
类包括一个额外的字段, salesbonus
并重写该方法 CalculatePay
以考虑它。
class TestOverride
{
public class Employee
{
public string Name { get; }
// Basepay is defined as protected, so that it may be
// accessed only by this class and derived classes.
protected decimal _basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
Name = name;
_basepay = basepay;
}
// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return _basepay;
}
}
// Derive a new class from Employee.
public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal _salesbonus;
// The constructor calls the base-class version, and
// initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay, decimal salesbonus)
: base(name, basepay)
{
_salesbonus = salesbonus;
}
// Override the CalculatePay method
// to take bonus into account.
public override decimal CalculatePay()
{
return _basepay + _salesbonus;
}
}
static void Main()
{
// Create some new employees.
var employee1 = new SalesEmployee("Alice", 1000, 500);
var employee2 = new Employee("Bob", 1200);
Console.WriteLine($"Employee1 {employee1.Name} earned: {employee1.CalculatePay()}");
Console.WriteLine($"Employee2 {employee2.Name} earned: {employee2.CalculatePay()}");
}
}
/*
Output:
Employee1 Alice earned: 1500
Employee2 Bob earned: 1200
*/
C# 语言规范
有关详细信息,请参阅 C# 语言规范的 Override 方法部分。
有关协变返回类型的详细信息,请参阅 功能建议说明。