Why do we use virtual and override?

前端 未结 4 1473
情话喂你
情话喂你 2020-12-29 07:28

Why do we use override and virtual if it gives the same effect when we dont use override and virtual?

example 1:

class BaseClass
{
    public virtual         


        
4条回答
  •  被撕碎了的回忆
    2020-12-29 08:10

    Best example I can think of where this is useful is when you create your own object(class) and you have to add a list of that object to a combobox.

    When you add your object to the combobox you want to be able to control what text is displayed for each item. Object.toString is a virtual method. http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx and because of this you can override that method and set .toString to display the correct information about your object by overriding it.

    public MyClass()
    {
         private int ID;
         public override string ToString()
         {
             return "My Item:" + ID;
         }
    }
    

提交回复
热议问题