为什么C#编译器不能将枚举负值转换为枚举?

此代码不能与latest C# compiler一起编译:

public class Program
{
    public static void Main()
    {
        IntEnum a = (IntEnum)-1;
    }
}

public enum IntEnum : int { }

当你试图编译它时,它会引发

(3,22,3,29): Error CS0119: ‘IntEnum’ is a type, which is not valid in the given context

奇怪的是,将转换值更改为正数(例如4),或使用const值(例如int.MinValue),或者甚至用括号如(IntEnum)( – 1)包围值将编译并正常工作.但是,上述样本没有.

这有什么理由吗?是否有可能Roslyn可能错误地解析了代码,这就是为什么错误会被提升?

最佳答案
期望行为并记录以允许解析像(Var)-1这样的表达式.

Compiler Error CS0075进入规范细节(我希望你能得到这个错误/除了CS0119):

To cast a negative value, you must enclose the value in parentheses
If you are casting using a keyword that identifies a predefined type, then you do not need parentheses. Otherwise, you must put the parentheses because (x) –y will not be considered a cast expression. From the C# Specification, Section 7.6.6:

From the disambiguation rule it follows that, if x and y are identifiers, (x)y, (x)(y), and (x)(-y) are cast-expressions, but (x)-y is not, even if x identifies a type. However, if x is a keyword that identifies a predefined type (such as int), then all four forms are cast-expressions (because such a keyword could not possibly be an expression by itself).

转载注明原文:为什么C#编译器不能将枚举负值转换为枚举? - 代码日志