Вы находитесь на странице: 1из 2

override

Visual Studio .NET 2003


Other Versions
* Visual Studio 2010
* Visual Studio 2008
* Visual Studio 2005
Use the override modifier to modify a method, a property, an indexer, or an even
t. An override method provides a new implementation of a member inherited from a
base class. The method overridden by an override declaration is known as the ov
erridden base method. The overridden base method must have the same signature as
the override method.
You cannot override a non-virtual or static method. The overridden base method m
ust be virtual, abstract, or override.
An override declaration cannot change the accessibility of the virtual method. B
oth the override method and the virtual method must have the same access level m
odifier.
You cannot use the following modifiers to modify an override method:
new static virtual abstract
An overriding property declaration must specify the exact same access modifier,
type, and name as the inherited property, and the overridden property must be vi
rtual, abstract, or override.
For more information on accessing the base class members, see 7.5.8 Base access.
For more information on overriding methods, see 10.5.4 Override methods.
Example
See the example for the virtual keyword.
From within the derived class that has an override method, you still can access
the overridden base method that has the same name by using the base keyword. For
example, if you have a virtual method MyMethod(), and an override method on a d
erived class, you can access the virtual method from the derived class by using
the call:
Copy
base.MyMethod()
Compare this to the C++ way, where you use the scope resolution operator (::) an
d the base class name, for example:
Copy
My_Base_Class_Name::MyMethod()
Example
In this example, there is a base class, Square, and a derived class, Cube. Becau
se the area of a cube is the sum of the areas of six squares, it is possible to
calculate it by calling the Area() method on the base class.
Copy
// cs_override_keyword.cs
// Calling overriden methods from the base class
using System;
class TestClass
{
public class Square
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double Area()
{
return x*x;
}
}
class Cube: Square
{
// Constructor:
public Cube(double x): base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (6*(base.Area()));
}
}
public static void Main()
{
double x = 5.2;
Square s = new Square(x);
Square c = new Cube(x);
Console.WriteLine("Area of Square = {0:F2}", s.Area());
Console.WriteLine("Area of Cube = {0:F2}", c.Area());
}
}
Output
Copy
Area of Square = 27.04
Area of Cube = 162.24

Вам также может понравиться