考慮這個簡單的程序,編譯在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));
有人可以用於提供一個合理的解釋,這在插入使用字符串表達式時假陽性?
不知道你可以在enum上使用'd'格式說明符,而不必先投射。感謝您的解決方法。當然,我沒有在我的問題中提到這個,但是在我的真實世界問題中,我的字符串看起來更像這個'$'方向是{(int)Direction.Right:X8}「'。所以我確實需要演員,否則我得到一個'FormatException'。但是這很有用,謝謝! – sstan