简体   繁体   中英

C# function with variable number of arguments causes confusion when multiple overloads available

    public string GetErrorMessage(params object[] args)
    {
        return GetErrorMessage("{0} must be less than {1}", args);
    }

    public string GetErrorMessage(string message, params object[] args)
    {
        return String.Format(message, args);
    }

Here is the call

    Console.WriteLine(GetErrorMessage("Ticket Count", 5));

Output

Ticket Count

This means, it invokes the 2nd overload of the method with 2 parameters: message, variable number of object arguments.

Is there a way to force it to invoke first overload rather than second?

Console.WriteLine(GetErrorMessage(new object[] { "Ticket Count", 5 }));

The problem you are seeing is caused because the first item in your method call is a string and therefore will alway match the second method call. You can do 1 of the following to get around the problem:

If the order of the args is not important you could simply make sure that the first item is not a string :

this.GetErrorMessage(5, "Ticket Count");

Or you can cast the string to an object :

this.GetErrorMessage((object)"Ticket Count", 5);

You could always make this call however it does break the whole purpose of using params :

this.GetErrorMessage(new object[] {"Ticket Count", 5 });

No, there is no way to take full advantage of the params keyword for the situation you are describing. The compiler sees a more specific, better fit during overload resolution because of the string argument provided. So the only way to force it into the first form is to explicitly force the string into an object [] . Something like this:

Console.WriteLine(GetErrorMessage(new object[] { "Ticket Count", 5 }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM