.Net inheritance and method overloading

前端 未结 5 970
清酒与你
清酒与你 2021-02-20 11:15

Here is a code sample:

class Program
{
    static void Main(string[] args)
    {
        var obj = new DerivedClass();
        obj.SomeMethod(5);
    }
}

class          


        
5条回答
  •  生来不讨喜
    2021-02-20 12:00

    Edit after comments: True, I probably did not answer the exact question properly, so let me try now:

    The method call in the original code matches the signature of both methods (both in the base, and the derived class), since the parameter 5 could be either an int or a long in this case. The base method however, is not marked as virtual (which would allow overriding), and the "derived" method is not really derived, since it is not marked with override.

    NOTE however, that even if you did mark it as override, you would get an error, since in reality, the two method signatures are not equivalent: One takes an int, while the other takes a long type. This will result in a compile-time error with the messsage: "no suitable method found to override".

    The rest should hopefully become clear if you read the rest of my original answer below.


    Original answer:

    There are several things to note here:

    1) Your methods have different signatures; one takes a long, and the other takes an int

    2) You haven't marked your methods virtual or override.

    An edited version of your code with some comments might make it more clear how this stuff works:

    internal class Program
    {
        private static void Main(string[] args)
        {
    
            var obj = new DerivedClass();
            // That is the same as:
            //DerivedClass obj = new DerivedClass();
    
            // Will call the base method, since that now matches the
            // signature (takes an int parameter). DerivedClass simply
            // does not HAVE a method with that signature on it's own:
            obj.SomeMethod(5); // will output "base with int"
    
            // Now call the other method, which IS defined in DerivedClass, 
            // by appending an "l", to mark this as a Long:
            obj.SomeMethod(5l); // Will output "derived"
    
            // This would call the base method directly
            var obj2 = new BaseClass();
            obj2.SomeMethod(5l); 
    
            Console.ReadKey();
        }
    }
    
    internal class BaseClass
    {
        internal void SomeMethod(int a)
        {
            Console.WriteLine("base with int");
        }
    
        // Added method for the example:
        // Note that "virtual" allows it to be overridden
        internal virtual void SomeMethod(long a)
        {
            Console.WriteLine("base with long");
        }
    }
    
    internal class DerivedClass : BaseClass
    {
        // Note: Overrides the base method now
        internal override void SomeMethod(long a)
        {
            Console.WriteLine("derived");
        }
    }
    

提交回复
热议问题