I have following code:
Dim len As Int32 = 1000
Dim rdlen As Int64 = 2000000000000
Dim totlen As Int64
Which example is the correct way to use System.Convert.ToInt64 function?
Example one:
totlen = System.Conver开发者_StackOverflow中文版t.ToInt64(rdlen + len)
Example two:
totlen = rdlen + System.Convert.ToInt64(len)
Both expressions will evaluate to the same thing.
There is an implicit conversion between Int32
and Int64
, so even the following works:
totlen = rdlen + len
I think both examples are correct. At least in c#.
When A and B is of different integer type, compiler should convert both of them to the same type in order to do A+B. So it converts both to Int64 before computing A+B.
It works either way, and it works without the conversion also, as the 32 bit integer will be widened to work with the 64 bit integer.
You shouldn't use the Convert
class to do such conversion anyway, you should just use the cast syntax.
If you want to show in the code exactly what's happening, or if you want to make sure that it really happens the way you indend it, you cast the 32 bit integer to 64 bits before the addition:
totlen = rdlen + (Int64)len;
It will however produce the exact same code as this, as the 32 bit integer will be implicitly converted:
totlen = rdlen + len;
精彩评论