C#整数或对象对双精度转换错误说明
以下代码在最后一次分配时失败:
The below code fails at the last assignment:
static void Main(string[] args)
{
int a = 5;
object b = 5;
System.Diagnostics.Debug.Assert( a is int && b is int );
double x = (double)a;
double y = (double)b;
}
如果a和b均为 int
,此错误的原因是什么?
If both a and b are int
, what is the cause of this error?
这是一个非常常见的问题。参见 http://blogs.msdn。 com / b / ericlippert / archive / 2009/03/19 / representation-and-identity.aspx 进行解释。
This is an extremely frequently asked question. See http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx for an explanation.
代码段:
我对C#强制转换运算符有很多疑问。我最常遇到的问题是:
I get a fair number of questions about the C# cast operator. The most frequent question I get is:
short sss = 123;
object ooo = sss; // Box the short.
int iii = (int) sss; // Perfectly legal.
int jjj = (int) (short) ooo; // Perfectly legal
int kkk = (int) ooo; // Invalid cast exception?! Why?
为什么?因为装箱的 T
只能取消装箱到 T
。 (*)取消装箱后,它只是可以正常转换的值,因此双精度转换就可以正常工作。
Why? Because a boxed T
can only be unboxed to T
. (*) Once it is unboxed, it’s just a value that can be cast as usual, so the double cast works just fine.
(*)或 Nullable< T>
。