4

I am working with some code that has seven overloads of a function TraceWrite:

void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, string Data = "");
void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, bool LogToFileOnly, string Data = "");
void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, string PieceID, string Data = "");
void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, LogWindowCommandENUM LogWindowCommand, string Data = "");
void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, bool UserMessage, int UserMessagePercent, string Data = "");
void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, string PieceID, LogWindowCommandENUM LogWindowCommand, string Data = "");
void TraceWrite(string Application, LogLevelENUM LogLevel, string Message, LogWindowCommandENUM LogWindowCommand, bool UserMessage, int UserMessagePercent, string Data = "");

(All public static, namespacing noise elided above and throughout.)

So, with that background:
1) Elsewhere, I call TraceWrite with four arguments: string, LogLevelENUM, string, bool, and I get the following errors:

error CS1502: The best overloaded method match for 'TraceWrite(string, LogLevelENUM, string, string)' has some invalid arguments
error CS1503: Argument '4': cannot convert from 'bool' to 'string'

Why doesn't this call resolve to the second overload? (TraceWrite(string, LogLevelENUM, string, bool, string = ""))

2) If I were to call TraceWrite with string, LogLevelENUM, string, string, which overload would be called? The first or the third? And why?

4

2 回答 2

2

编译器将选择重载#1,因为它与参数数量和签名完全匹配。

于 2010-06-17T13:45:10.660 回答
0

你的重载很糟糕,你应该在它们之间做出更多的改变。编译器无法知道您是指第一个还是第三个。

第三个参数的最后一个参数应该没有默认值,第一个参数在最后一个字符串之前应该有一个不同的非字符串参数,或者第三个参数的 PieceID 参数应该是一个 int。

有一个不同的可能更好的解决方案:使用多个默认值。您有很多默认值,它们应该减少重载的数量。使用多个默认值,您可以调用仅指定最后一个值的方法。希望您可以将重载次数减少到 1 或 2。

public static int add(int a = 0, int b = 0)
{
    return a + b;
}
add(b: 1);
于 2010-06-17T13:49:48.403 回答