Will 1 + 2 be performed during run- or compile-time?Reason for asking:I think most people sometimes use a literal without specifying why it has been used or what it means because they do not want to waste a bit performance by running the calculation and I believe the calculate happens during compiletime and has no effect on performance:int nbr = 31536000; //What the heck is that?代替int nbr = 365 * 24 * 60 * 60; //I guess you know what nbr is supposed to be now...推荐答案由于您的示例本质上是常量表达式(即它们仅由常量或按此类求值的构造组成),因此它们将在编译时进行评估.Since your examples are essentially constant expressions (i.e. they consist of only constants or constructs that evaluate as such), they will be evaluated at compile time. 常量表达式是可以在以下位置完全求值的表达式 编译时. A constant-expression is an expression that can be fully evaluated at compile-time.常量表达式的类型可以是以下之一:sbyte,byte,short,ushort, int,uint,long,ulong,char,float,double,decimal,bool,string, 任何枚举类型或null类型.The type of a constantexpression can be one of the following: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, any enumeration type, or the null type.在常量表达式中允许使用以下构造:The following constructs are permitted in constant expressions:文字(包括空文字).引用类和struct类型的const成员.引用枚举类型的成员.被括号化的子表达式,它们本身就是常量表达式.如果目标类型是上面列出的类型之一,则使用Cast表达式.预定义的+,–,!和~一元运算符.预定义的+,–,*,/,%,<<,>>,&,|,^,&&,||,==,!=,<,>,<=和>=二进制运算符,条件是每个操作数都具有上面列出的类型. ?:条件运算符.Literals (including the null literal).References to const members of class and struct types.References to members of enumeration types.Parenthesized sub-expressions, which are themselves constant expressions.Cast expressions, provided the target type is one of the types listed above.The predefined +, –, !, and ~ unary operators.The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.The ?: conditional operator. 这篇关于是否在编译时对C#中的文字进行算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-24 13:52