SoFunction
Updated on 2025-04-14

Virtual method and application scenario analysis in c#

concept

In C#,virtualKeywords are used to modify methods, properties, indexers or events. When a method is declared asvirtual, it means that the method can be override in the derived class. This enables derived classes to change the implementation of base class methods according to their own needs.

significance

  • Implement polymorphism: allows corresponding methods to be called according to the actual type of the object at runtime, enhancing the flexibility and scalability of the program. For example, different derived classes can have different implementations of the same virtual method, and the method version of the corresponding object type will be executed when called.
  • Code reuse and customization: The base class provides a general method implementation. If there are special needs of the derived class, the method can be rewrited, which not only reuses the code structure of the base class, but also realizes customization.

Application scenarios

  • Framework design: Define some virtual methods in the framework for developers to rewrite according to specific business needs when using the framework. For example, in Core's middleware design, there are many rewritable virtual methods.
  • Behavior customization in class hierarchy: When there is a class inheritance system and the derived class needs to change the behavior of certain methods of the base class, the virtual method can be used. For example, a graph drawing base class has a virtual method to draw graphics. Different derived graph classes (such as circle classes and rectangles) can override this method to implement their respective drawing logic.

Pros and cons

  • Advantages
    • Flexibility: Provides the ability to runtime polymorphism, allowing programs to execute appropriate code according to actual object types and adapt to different business scenarios.
    • Extensibility: It is convenient to extend or modify methods in derived classes without modifying the base class code, and it complies with the principle of opening and closing.
  • Disadvantages
    • Performance overhead: Since it involves runtime method search and dynamic binding, it will have certain performance losses compared to non-virtual methods. However, in most application scenarios, this performance impact is not obvious.
    • Adding complexity: In a complex class inheritance hierarchy, excessive virtual method rewriting can make code logic difficult to understand and maintain.
  • Things to note
    • Method signature consistency: When a derived class overrides a virtual method, the method signature (including return type, method name, parameter list) must be exactly the same as the virtual method in the base class, otherwise it will be regarded as a new method rather than a rewrite.
    • Reasonable use: Do not overuse virtual methods, only use them where you really need to customize the derived classes to avoid unnecessary complexity.
    • Base class method call: In the method overridden by derived class, if you need to call the implementation of the base class, you can use base. method name() to call it.

Specific code examples

csharp

// Base classclass Animal
{
    // Define virtual methods    public virtual void Speak()
    {
        ("The animal makes a sound");
    }
}
// Derived classesclass Dog : Animal
{
    // Rewrite the virtual method of the base class    public override void Speak()
    {
        ("Woom wool");
    }
}
class Cat : Animal
{
    public override void Speak()
    {
        ("Meow Meow");
    }
}
class Program
{
    static void Main()
    {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        (); // Output: Woof, Woof, Woof, Woof        (); // Output: Meow Meow Meow    }
}

In the above code,AnimalIn the classSpeakThe method is declared asvirtualDogClass andCatThe class rewrites the method separately to realize their own different calls. existMainIn the method, call through variables of the base class typeSpeakWhen a method, it will be based on the actual object type (DogorCat) Perform the corresponding rewrite method.

This is all about this article about virtual methods in C#. For more related contents of C# virtual methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!