Resolving Ambiguities with Optional Parameters and Named Arguments

后端 未结 3 745
北恋
北恋 2021-01-23 07:36

I have two methods on my project as defined below:

void Person(int ID, double height = 0.0, string team = \"Knights\")
{
   //my codes
}
void Person(int ID, d         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 07:54

    The C# specification says in §7.5.3.2, regarding choosing a better overload:

    If all parameters of [Method A] have a corresponding argument whereas default arguments need to be substituted for at least one optional parameter in [Method B] then [Method A] is better than [Method B].

    When you specify a value for all parameters:

    Person(1, 2.5, "Dark Ghost");
    

    The above rule makes the first method a better candidate, and it is chosen as the correct overload.

    When you don't:

    Person(1, 46.5);
    

    The rule does not apply, and the overload resolution is ambiguous.


    You might say, why not choose the one with the least parameters? That seems fine at first, but causes a problem when you have something like this:

    void Foobar(int a, string b = "foobar")
    {
    }
    
    void Foobar(int a, int b = 0, int c = 42)
    {
    }
    
    ...
    
    Foobar(1);
    

    In this case there's no valid reason to choose the first one over the second. Thus you can only properly resolve this by supplying a value for all parameters.

提交回复
热议问题