簡體   English   中英

C# 4 中的重載分辨率和可選參數

[英]Overload Resolution and Optional Parameters in 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) 在其他地方,我使用四個參數調用TraceWritestring, 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,因為它與參數數量和簽名完全匹配。

您的重載是不好的,您應該在它們之間做更多的改變。 編譯器無法知道您是第一個還是第三個。

第三個參數應該沒有最后一個參數的默認值,第一個參數應該在最后一個字符串之前具有不同的非字符串參數,或者第三個參數的PieceID參數應為int。

有另一種可能更好的解決方案:使用多個默認值。 您有很多默認值,它們應減少重載次數。 使用多個默認值,您可以僅指定最后一個值來調用方法。 希望您可以將重載次數減少到1或2。

public static int add(int a = 0, int b = 0)
{
    return a + b;
}
add(b: 1);

對於第二個問題,您的調用將被解析為第一個重載,因為它的簽名具有較少的參數。

如果您希望將其解析為第三個重載,請在調用中使用命名參數,例如:

TraceWrite("string", LogLevelENUM.Level, "string", PieceID: "string");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM