简体   繁体   English

C#分配问题

[英]C# assignment question

In the following snippet: 在以下代码段中:

long frameRate = (long)(_frameCounter / this._stopwatch.Elapsed.TotalSeconds);

Why is there an additional (long)(...) to the right of the assignment operator? 为什么赋值运算符右边还有一个(长)(...)?

The division creates a double-precision floating point value (since TimeSpan.TotalSeconds is a double ), so the cast truncates the resulting value to be integral instead of floating point. 除法创建一个双精度浮点值(因为TimeSpan.TotalSeconds是一个double ),因此转换将结果值截断为积分而不是浮点。 You end up with an approximate but whole number of frames-per-second instead of an exact answer with fractional frames-per-second. 最终得到一个近似但整数帧的每秒,而不是每秒小数帧的精确答案。

If frameRate is used for display or logging, the cast might just be to make the output look nicer. 如果frameRate用于显示或记录,则强制转换可能只是为了使输出看起来更好。

It's an explicit conversion (cast) that converts the result of the division operation to a long . 它是一个显式转换(强制转换),它将除法运算的结果转换为long

See: Casting and Type Conversions 请参阅: 转换和类型转换

Because the result of the calculation relates to what types the variables are that are being used. 因为计算的结果与正在使用的变量的类型有关。 If the compiler thinks the result type is not a long because of the types being acted on, then you need to cast your result. 如果编译器认为结果类型不long因为要执行的类型,则需要转换结果。

Note that casting your result may incur loss of accuracy or values. 请注意,投射结果可能会导致精度或值丢失。 The bracketed cast (long) is an explicit cast and will not generate any errors if, say, you tried to fit "1.234" into a long , which could only store "1". 括号内的投(long)是一个明确的演员和比如说,如果你试图以适应“1.234”成不会产生任何错误long ,这只能存储“1”。

In my opinion there could be a few reasons: 在我看来,可能有几个原因:

  1. At least one of types in expression is not integer type (I don't think so). 表达式中至少有一种类型不是整数类型(我不这么认为)。
  2. Developer wanted to highlighted that result is long type (makes the result type clear for reader -- good reason). 开发人员希望突出显示结果是long类型(使结果类型为读者清楚 - 很好的理由)。
  3. Developer was not sure what is the result of expression and wanted to make sure it will be long (it's better to make sure, that hopes, it will work). 开发人员不确定表达的结果是什么,并希望确保它会很long (最好确保,希望,它会起作用)。

I believe it was 3 :). 我相信这是3 :)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM