2014-11-22 60 views
0

因此,我下面的代碼:CA1806 DoNotIgnoreMethodResults錯誤地引發?

[Conditional("DEBUG")] 
internal static void WriteGLResult(string methodName, object result, 
    params object[] args) 
{ 
    string message = String.Format(CultureInfo.InvariantCulture, "{0}({1}) = {2}", 
     methodName, String.Join(", ", args), result); 
    Write(LogType.Information, Category.GLResult, 2, message); 
} 

我清楚地分配String.Format()結果變量message。之後我也將該實例傳遞給Write方法。然而,CA1806升高:

不要忽略方法結果

'Log.WriteGLResult(字符串,對象,params對象[])' 電話「的String.format(的IFormatProvider,字符串,params對象[ ])',但不使用該方法返回的新字符串實例。通過該實例作爲參數傳遞給另一個方法,實例分配給一個變量,或刪除的通話,如果它是unnecessary.`

在叫Write方法,我還使用字符串,命名有format ,因爲它是這樣使用的:

[Conditional("DEBUG")] 
private static void Write(LogType logType, Category category, int stackTraceFrameSkips, 
    string format, params object[] args) 
{ 
    // ... 
    string message = String.Format(CultureInfo.InvariantCulture, format, args); 
    // ... 
} 

我不知道如何解決這個警告。我懷疑CA錯誤地提出了這個問題。

你能幫我嗎?

+1

如何定義「寫入」?我問,因爲我的第一個猜測是它應用了['ConditionalAttribute'](http://msdn.microsoft.com/zh-cn/library/system.diagnostics.conditionalattribute%28v=vs.110%29.aspx)並且在CA確定是否曾經使用過「消息」之前呼叫結束。你可以嘗試提供一個最小化的完整程序,它有你描述的問題嗎? – hvd 2014-11-22 23:04:45

+0

@ hvd:是的,就是這樣。所有的寫入調用(這個和被調用的)都用'[Conditional(「DEBUG」)]'屬性裝飾。如果我沒有這些建設,我不會收到警告。我將它添加到我的問題中的片段。添加它作爲答案,我會接受。 =) – 2014-11-22 23:10:54

回答

1

從註釋展開:

由於Write被定義爲

[Conditional("DEBUG")] 
private static void Write(LogType logType, Category category, int stackTraceFrameSkips, 
    string format, params object[] args) 

這意味着到Write呼叫將不定義DEBUG符號時,可以完全除去。代碼分析稍後運行,到那個時候它可以確定(正確)從未使用message

的東西,既不警告在調試也不在發佈模式,您威力要調用String.Format直接移動到方法的參數:

Write(LogType.Information, Category.GLResult, 2, 
    String.Format(CultureInfo.InvariantCulture, "{0}({1}) = {2}", 
    methodName, String.Join(", ", args), result)); 

這應該確保String.Format只調用時將會調用Write

+0

偉大的解決方案,完美的工作。 – 2014-11-22 23:25:04