2015-08-25 16 views
5

考慮這個簡單的程序,編譯在Visual Studio 2015年罰款:的Visual Studio 2015年:無效的 「演員是多餘的」,在插值字符串表達式警告

public class Program 
{ 
    enum Direction 
    { 
     Up, 
     Down, 
     Left, 
     Right 
    } 

    static void Main(string[] args) 
    { 
     // Old style 
     Console.WriteLine(string.Format("The direction is {0}", Direction.Right)); 
     Console.WriteLine(string.Format("The direction is {0}", (int)Direction.Right)); 

     // New style 
     Console.WriteLine($"The direction is {Direction.Right}"); 
     Console.WriteLine($"The direction is {(int)Direction.Right}"); 
    } 
} 

...它輸出的預期:

The direction is Right 
The direction is 3 
The direction is Right 
The direction is 3 

但是,Visual Studio的2015年不斷暗示這條線 「快速行動」 的具體做法是:

// "Cast is redundant" warning 
Console.WriteLine($"The direction is {(int)Direction.Right}"); 

它堅持認爲(int)「鑄造是多餘的」,並建議作爲「刪除不必要的鑄件」的潛在修復,這當然是錯誤的,因爲它會改變結果。

有趣的是,它並沒有給我的等值聲明任何警告:

// No warnings. 
Console.WriteLine(string.Format("The direction is {0}", (int)Direction.Right)); 

有人可以用於提供一個合理的解釋,這在插入使用字符串表達式時假陽性?

回答

8

這是a known bug

一個臨時的解決已提出了平均時間:

對於現在人們經歷VS2015這個bug,解決方法是抑制受影響的項目的屬性頁的Build標籤警告IDE0004。

此問題已於2015年9月9日在PR 5029已被修復併合併成爲主人。

3

的顯式類型轉換不必要的方式 - 你可以(並且可能應該)使用格式說明:

$"The direction is {Direction.Right:d}" 

但是,是的,警告是愚蠢的 - 它應該表明這種變化,不僅僅是刪除(int)。編譯器有很多奇怪的東西 - 幸運的是,大多數似乎很容易解決。

+0

不知道你可以在enum上使用'd'格式說明符,而不必先投射。感謝您的解決方法。當然,我沒有在我的問題中提到這個,但是在我的真實世界問題中,我的字符串看起來更像這個'$'方向是{(int)Direction.Right:X8}「'。所以我確實需要演員,否則我得到一個'FormatException'。但是這很有用,謝謝! – sstan

相關問題