How to use "override" in C sharp?

2007-10-22 6:04 am
How to use "override" in C sharp?

回答 (1)

2007-10-22 3:18 pm
✔ 最佳答案
override is used in a derived class to modify the method, property or event of the base class so that the method, property or event has a different implementation from that of the base class.

To use the keyword virtual and override, you must understand inheritance.

Example:

' this is the base class
public class Square
{
public virtual double Area(double x)
{
return x * x;
}
}


' this is the derived class from Square
public class Cube: Square
{
public override double Area(double x)
{
return 6 * x * x;
}
}

Explanation:
Cube is derived from Square, meaning that Cube inherits the methods, properties of Square. Square has a method called Area and Cube also has a method with the same name but Square's Area is not the same is Cube's Area. Therefore Cube's area cannot use the same code as Square and Cube must have its own code in method Area. In this case Cube's Area overries Square's Area. The base class's method must have the virtual keyword in order for it to be overridden.


收錄日期: 2021-04-25 20:33:10
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20071021000051KK05538

檢視 Wayback Machine 備份