gpt4 book ai didi

C# int- or object-to-double 转换错误解释

转载 作者:太空狗 更新时间:2023-10-29 19:48:36 25 4
gpt4 key购买 nike

以下代码在最后一次赋值时失败:

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,这个错误的原因是什么?

最佳答案

这是一个非常常见的问题。参见 https://ericlippert.com/2009/03/03/representation-and-identity/寻求解释。


片段:

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?

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.

(*) Or Nullable<T>.

关于C# int- or object-to-double 转换错误解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10387195/

25 4 0
文章推荐: C# 子类返回类型的协方差
文章推荐: c++ - std::vector 保留方法是否需要 Object 类的复制构造函数?