Virtual (virtual), virtual (virtual)
Virtual)
Virtual keywords are used to modify methods, properties, indexers, or event declarations, and allow them to be rewritten in a derived class.
Read a piece of code:
UsingSystem;
Class
{
PublicVoidF()
{
Console.WriteLine("A.F ");
}
}
Class B:
{
PublicNewVoidF() // Note the new Keyword
{
Console.WriteLine("B. F ");
}
}
Class Test
{
Static voidMain()
{
B B =NewB();
A a = B;
A.F();
B.F();
}
}
Output: A.F
B. F
If the above Code is in memory:
Let's look at another piece of code:
UsingSystem;
Class
{
PublicVirtual voidF()
{
Console.WriteLine("A.F ");
}
}
Class B:
{
PublicOverride voidF()
{
Console.WriteLine("B. F ");
}
}
Class C: B
{
PublicNewVoidF()
{
Console.WriteLine("C. F ");
}
}
Class Test
{
Static voidMain()
{
C c =NewC();
A a = c;
A.F();
}
}
Output: B. F
-> The member of the base class searches for the inheritance chain, finds the member before the new modifier, and calls the member.
Polymorphism ):
Polymorphism refers to the ability of two or more objects of different classes to make different responses to the same message.
-> Virtual and override keywords: Polymorphism provides a method for subclass to customize how to implement the methods defined by the base class;
See the following code:
UsingSystem;
Class Employee
{
ProtectedString _ name;
PublicEmployee(){}
PublicEmployee(String name)
{
_ Name = name;
}
PublicVirtual voidStartWork()
{
Console.WriteLine(_ Name + "start as work ");
}
}
Class Manager: Employee
{
PublicManager(String name ):Base(Name ){}
PublicOverride voidStartWork()
{
Base.StartWork(); // Pay attention to the usage of base
Console.WriteLine("Issue a task ");
}
}
Class Seller: Employee
{
PublicSeller(String name ):Base(Name ){}
PublicOverride voidStartWork()
{
Base.StartWork();
Console.WriteLine("Sales product ");
}
}
Class Test
{
Static voidMain()
{
Employee [] emp =NewEmployee [2];
Emp [0] =NewManager("James ");
Emp [1] =NewSeller("Li Si ");
Foreach(Employee eInEmp)
{
E.StartWork();
}
}
}