编程语言
首页 > 编程语言> > C#4中的过载分辨率和可选参数

C#4中的过载分辨率和可选参数

作者:互联网

我正在使用一些代码,它有一个函数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 = "");

(所有公共静态,命名空间噪音在上面和之后都没有.)

那么,有了这样的背景:
1)在其他地方,我用四个参数调用TraceWrite:string,LogLevelENUM,string,bool,我得到以下错误:

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'

为什么这个调用不能解决第二个重载? (TraceWrite(string,LogLevelENUM,string,bool,string =“”))

2)如果我用字符串,LogLevelENUM,字符串,字符串调用TraceWrite,将调用哪个重载?第一个还是第三个?为什么?

解决方法:

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

标签:c,optional-parameters,overloading,overload-resolution
来源: https://codeday.me/bug/20190705/1384328.html