virtual c#
时间: 2023-08-27 17:13:26 浏览: 100
visual C#
4星 · 用户满意度95%
Virtual in C# is a keyword that is used to modify a method property, or event declaration. When a method, property, or event is marked as virtual, it means that it can be overridden in derived classes using the override keyword. This allows for polymorphic behavior, where a derived class can provide its own implementation of the virtual member.
For example, consider a base class called Animal with a virtual method called MakeSound:
```csharp
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound.");
}
}
```
You can then create derived classes that override the MakeSound method to provide their own sound:
```csharp
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog barks.");
}
}
public class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat meows.");
}
}
```
By marking the MakeSound method as virtual in the base class, you allow derived classes to provide their own implementation of the method. This allows for greater flexibility and customization in your code.
阅读全文