Resolving Ambiguities with Optional Parameters and Named Arguments

后端 未结 3 744
北恋
北恋 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:50

    TL:DR The first method (most specific) will be called because in that case no parameter needs to be bound using default values.

    For an in-depth discussion refer to this article.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-23 08:11

    If possible, the one which can be applied without default parameters is called.

    In the first case

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

    First method is called.

    In the second case:

    Person(1, 46.5);
    

    It will simply result in build error. "The call is ambiguous between the following methods or properties: Test.Person(int, double, string) and Person(int, double, string, int)".

    0 讨论(0)
提交回复
热议问题