What is the difference between base reference type vs derived reference type

后端 未结 6 824
清酒与你
清酒与你 2021-01-07 13:20
class Dog
{
}
class BullDog : Dog
{
}
class Program
{
    static void Main()
    {
        Dog dog2 = new BullDog();
        BullDog dog3 = new BullDog();
    }
}
         


        
6条回答
  •  孤独总比滥情好
    2021-01-07 13:54

    lets define an other class :

    class OtherDog : Dog 
    {
    
    }
    

    now you can define a list like this :

    C# :

    List Dogs = new List();
    Dogs.Add(new BullDog());
    Dogs.Add(new OtherDog());
    

    you have a list with Dog type , but can add to it BullDog and OtherDog type to it

    this is one of the OOP subjects name "Polymorphism"

    ex2 :

    lets think you want to develop a paint :

    class Shape ()
    {
    
        virtual public void Draw()
        {
        }
    
    }
    
    class Rectangle : Shape ()
    {
    
        override public void Draw()
        {
        }
    
    }
    
    class Circle : Shape ()
    {
    
        override public void Draw()
        {
        }
    
    }
    
    
    void main ()
    {
    
        List Shapes = new List();
        Shapes.Add(new Rectangle());
        Shapes.Add(new Circle());
    
        Shape[1].Draw(); //Draw a rectangle
        Shape[2].Draw(); // Draw a circle
    
    }
    

    if you need more details comment me to edit my reply for more details

    thansk , Ali

提交回复
热议问题