What Does “Overloaded”/“Overload”/“Overloading” Mean?

前端 未结 8 1222
清歌不尽
清歌不尽 2020-12-09 10:33

What does \"Overloaded\"/\"Overload\" mean in regards to programming?

8条回答
  •  轮回少年
    2020-12-09 11:05

    Basic Concept

    Overloading, or "method overloading" is the name of the concept of having more than one methods with the same name but with different parameters.

    For e.g. System.DateTime class in c# have more than one ToString method. The standard ToString uses the default culture of the system to convert the datetime to string:

    new DateTime(2008, 11, 14).ToString(); // returns "14/11/2008" in America
    

    while another overload of the same method allows the user to customize the format:

    new DateTime(2008, 11, 14).ToString("dd MMM yyyy"); // returns "11 Nov 2008"
    

    Sometimes parameter name may be the same but the parameter types may differ:

    Convert.ToInt32(123m);
    

    converts a decimal to int while

    Convert.ToInt32("123");
    

    converts a string to int.

    Overload Resolution

    For finding the best overload to call, compiler performs an operation named "overload resolution". For the first example, compiler can find the best method simply by matching the argument count. For the second example, compiler automatically calls the decimal version of replace method if you pass a decimal parameter and calls string version if you pass a string parameter. From the list of possible outputs, if compiler cannot find a suitable one to call, you will get a compiler error like "The best overload does not match the parameters...".

    You can find lots of information on how different compilers perform overload resolution.

提交回复
热议问题