是否在编译时对C#中的文字进行算术运算? [英] Are arithmetic operations on literals in C# evaluated at compile time?

查看:72
本文介绍了是否在编译时对C#中的文字进行算术运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简短的问题,但是我现在无法在网络上找到解决方案.

Very short question but I couldn't find a solution on the web right now.

int test = 1 + 2;

将在运行时还是编译时执行1 + 2?

问原因: 我认为大多数人有时会使用字面量,而没有说明使用该字面量的原因或含义,这是因为他们不想通过运行计算来浪费一点性能,并且我相信计算是在编译时进行的,并且对性能没有影响:

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#中的文字进行算术运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆