This compiles
var fourGb = (lon开发者_StackOverflow中文版g)4*1024*1024*1024;
But this fails
var fourGb = 4*1024*1024*1024;
With "The operation overflows at compile time in checked mode".
So if the compiler knows this will be an overflow why cant it infer that the variable type should be a long?
See http://msdn.microsoft.com/en-us/library/ctetwysk%28VS.80%29.aspx
You asked it to multiply a bunch of ints so the answer is an int according to the C# syntax. Use 'L' if you want a long.
var fourGb = 4L * 1024 * 1024 * 1024;
Imagine the uproar that would cause. "But the compiler can figure out an expression should be evaluated as long, why can't the runtime do it?"
And that's not going to happen, way too expensive.
It is essential that the compiler evaluates expressions the same way as the runtime. If that wasn't the case, editing a constant expression and replacing a constant with a variable could suddenly cause runtime failure. Hard to diagnose failure at that, non-constant expressions are unchecked by default.
I don't think it's a good idea to infer the type of variable by the calculation result.
It's the same in most languages:
- the datatypes of the expression follow precedence rules
- it's cast to "var" datatype on assignment
Any other behaviour would give unintended consequences
Arguably you've :
- restated "why do i get zero" for this:
double varname = 1/2
- duplicated his Instead of error, why don’t both operands get promoted to float or double?
精彩评论