Virtual functions

后端 未结 7 1540
清酒与你
清酒与你 2020-12-11 06:39

I don\'t really understand - when am I supposed to use virtual functions?I\'ll be glad if someone could explain it to me, thanks.

7条回答
  •  盖世英雄少女心
    2020-12-11 07:23

    You only need virtual functions if you've set up an inheritance chain, and you want to override the default implementation of a function defined in the base class in a derived class.

    The classic example is something as follows:

    public class Animal
    {
        public virtual void Speak()
        {
            Console.WriteLine("...");
        }
    }
    
    public class Dog : Animal
    {
        public override void Speak()
        {
            Console.WriteLine("Bow-wow");
        }
    }
    
    public class Human : Animal
    {
        public override void Speak()
        {
            Console.WriteLine("Hello, how are you?");
        }
    }
    

    Both the Dog and Human classes inherit from the base Animal class, because they're both types of animals. But they both speak in very different ways, so they need to override the Speak function to provide their own unique implementation.

    In certain circumstances, it can be beneficial to use the same pattern when designing your own classes because this enables polymorphism, which is essentially where different classes share a common interface and can be handled similarly by your code.

    But I'll echo what others have suggested in the comments: learning object-oriented programming properly is not something you're going to be able to do by asking a few Stack Overflow questions. It's a complicated topic, and one well-worth investing your time as a developer learning. I highly advise picking up a book on object-oriented programming (and in particular, one written for the C# language) and going through the examples. OOP is a very powerful tool when used correctly, but can definitely become a hindrance when designed poorly!

提交回复
热议问题