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

后端 未结 6 779
清酒与你
清酒与你 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:50

    Normally when using inheritance you will also use overloading.

    But consider the following:

        static void Main()
        {
            Dog dog = new BullDog();
            BullDog bulldog = new BullDog();
    
            dog.Execute();
            bulldog.Execute();
        }
    
        class Dog
        {
            public virtual void Execute()
            {
                Console.WriteLine("Execute Dog");
            }
        }
    
        class BullDog : Dog
        {
            public new void Execute() // use new instead of override
            {
                Console.WriteLine("Execute BullDog");
            }
        }
    

    This will print:

    Execute Dog
    Execute BullDog
    

    You need to define a sub type if you want to access functions that are only available for that type. If you want to use operator overloading the way it's meant (with the override operator) you can use this subclass behavior without worrying about the current type.

    --EDIT--

    You asked for the difference between:

    object a3 = new BullDog();
    BullDog a3 = new BullDog();
    

    Well, for starters, in the same scope this would give you a compiler error because a3 can't be defined twice. But let's say you define them in different scopes.

    On object a3 you can only call methods that are avaible on object (Equals, GetHashCode, ToString, GetType()). If you want to use methods on it that are only avaible in the Dog class, you have to cast it to a Dog.

     object a3 = new BullDog();
     BullDog a4 = new BullDog();
    
     if (a3 is Dog)
     {
         // only executes when a3 is a Dog
         // a3 is for the compiler still of type object, so you can't call any other methods on it
     }
    
     Dog d1 = a3 as Dog; // cast it to a dog
    
     if (d1 != null) // if d1 == null, then a3 was not of type dog and the cast returned null
     {
         d1.Execute(); // we know now that d1 is a dog and that it points to a dog instance so we can call a dog method on it.
     }
    
     a4.Execute();
    

提交回复
热议问题