override(C# 参考)

 

override(C# 参考)

 

要扩展或修改继承的方法、属性、索引器或事件的抽象实现或虚实现,必须使用 override 修饰符。

在此例中,类 Square 必须提供 Area 的重写实现,因为 Area 是从抽象的 ShapesClass 继承而来的。

abstract class ShapesClass

{

abstract public int Area();

}



class Square : ShapesClass

{

int x, y;

// Because ShapesClass.Area is abstract, failing to override

// the Area method would result in a compilation error.

public override int Area()

{

return x * y;

}

}

有关 override 关键字用法的更多信息,请参见使用 Override 和 New 关键字进行版本控制 以及了解何时使用 Override 和 New 关键字

override 方法提供从基类继承的成员的新实现。通过 override 声明重写的方法称为重写基方法。重写的基方法必须与 override 方法具有相同的签名。有关继承的信息,请参见继承

不能重写非虚方法或静态方法。重写的基方法必须是 virtualabstractoverride 的。

override 声明不能更改 virtual 方法的可访问性。override 方法和 virtual 方法必须具有相同的访问级别修饰符

不能使用修饰符 newstaticvirtualabstract 来修改 override 方法。

重写属性声明必须指定与继承属性完全相同的访问修饰符、类型和名称,并且被重写的属性必须是 virtualabstractoverride 的。

此示例定义了一个名为 Employee 的基类,和一个名为 SalesEmployee 的派生类。SalesEmployee 类包括一个额外的属性 salesbonus ,并重写方法 CalculatePay 以便将该属性考虑在内。

using System;

class TestOverride

{

public class Employee

{

public string name;



// Basepay is defined as protected, so that it may be

// accessed only by this class and derrived classes.

protected decimal basepay;



// Constructor to set the name and basepay values.

public Employee(string name, decimal basepay)

{

this.name = name;

this.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)

{

this.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.

SalesEmployee employee1 = new SalesEmployee("Alice",

1000, 500);

Employee employee2 = new Employee("Bob", 1200);



Console.WriteLine("Employee " + employee1.name +

" earned: " + employee1.CalculatePay());

Console.WriteLine("Employee " + employee2.name +

" earned: " + employee2.CalculatePay());

}

}
输出
Employee Alice earned: 1500

Employee Bob earned: 1200
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值