c# - C# 4 中的重载分辨率和可选参数

标签 c# overloading optional-parameters overload-resolution

我正在处理一些代码,该代码具有函数 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 = "");

(所有公共(public)静态、命名空间噪音从头到尾都被忽略了。)

所以,有了这样的背景:
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) 如果我用string, LogLevelENUM, string, string 调用TraceWrite,会调用哪个重载?第一还是第三?为什么?

最佳答案

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

关于c# - C# 4 中的重载分辨率和可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3061925/

相关文章:

c# - 为什么重载不起作用?

c# - 如何在 WPF 中创建带有可编辑文本框的 ListView ?

c# - Socket.UseOnlyOverlappedIO?

c++ - 类型推导后函数模板中的替换顺序是否有任何保证?

r - `...` 是什么类型的对象?

tsql - 在TransactSQL中,是否可以创建一个采用可变数量的参数(可选参数)的函数?

c++ - 是否可以指定一个空的 std::vector 作为默认参数?

c# - C#WebClient-查看源问题

c# - 如何在 .NET Core 中使用 IUserIdProvider?

c++ - C++ 类构造中的奇怪错误