Virtual methods - a method that in the base class is declared as virtual , while in the derived class have been covered (blocked) as override, using the same function names and parameters according to the number and type (parameter names may be different).
Example 1 - the base class level
class level
{
public virtual void Method ()
{
Console.WriteLine ("The method was called with the class level");
Program 1
class Program {
static void Main (string [] args)
{
Pa. = new Level ();
pA.Metoda ();
Result 1
Example 2 - a class derived from class levels PoziomB. The method has been replaced with the keyword override .
class level {
public virtual void Method () {
Console.WriteLine ("The method was called with the class level");
;}}
PoziomB class: Level
{public override void Method () {
; Console.WriteLine ("The method was called from class PoziomB");
}}
Program 2
static void Main (string [] args)
{
Level PoziomB pB = new ();
pB.Metoda ();
Result 2
Example 3 - a class derived from class PoziomB PoziomC. An appeal to the obscured methods using the keyword base.
class level {public virtual void Method () {
Console.WriteLine ("The method was called with the class level");
}}
PoziomB class: Level
{
public override void Method () {
Console.WriteLine ("Method has been called PoziomB class ");
}
}
class PoziomC : PoziomB
{
public override void Metoda()
{
base.Metoda();
}
}
Program 3
class Program
{
static void Main (string [] args) {
PoziomA PoziomC pc = new ();
pC.Metoda ();}
}
Results 3
Przykład 4 - Class wyprowadzona PoziomD z klasy Level. It is not required to override virtual methods in classes parents.
class level {public virtual void Method () {
Console.WriteLine ( "The method was called from the class level");
}}
PoziomD class: Level
{}
Program 4
static void Main (string [] args) {
pd = new PoziomA PoziomD ();
pD.Metoda ();}
}
Results 4
Example 5 - The level class derived from class levels. Potential error - not in the method override keyword ; method from the class level will not be called, passing as the type of base level. Only use the var keyword, or give as a base level will cause a call to the class level.
class level {public virtual void Method () {
Console.WriteLine ("The method was called with the class level");
}}
Class Level: Level
{
public void method () {
Console.WriteLine ("The method was called with the class level");
}
}
Program 5
class Program
{
static void Main(string[] args)
{
PoziomA pE = new PoziomE();
pE.Metoda();
}
}
Result 5
0 comments:
Post a Comment