为什么垂头丧气在运行时出现故障 [英] why downcast fails at runtime

查看:159
本文介绍了为什么垂头丧气在运行时出现故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么下面沮丧的失败@运行时间:

I want to know why below downcast fails @ run time:

案例1:

Object y = 10.23;
Console.WriteLine(y.GetType()); //System.Double
int z = (int)y;// fails @ runtime
Console.ReadKey();



案例2:

case 2:

Double y = 10.23;
Console.WriteLine(y.GetType());//System.Double
int z = (int)y;//success
Console.ReadKey();

在这两种情况下y的类型是System.Double,为什么仍然在downcst第一案失败?

In both the cases the type of y is System.Double, still why downcst fails in first case?

推荐答案

在第一个例子;拆箱(大家展示一下)是的不同以向下转换或转换;这也许是不幸的是,C#使用所有3个相同的语法。

In the first example; unboxing (what you show) is different to downcasting or conversion; it is perhaps unfortunate that C# uses the same syntax for all 3.

必须拆箱值类型(如int /双)正确。或者使用 Convert.ToInt32(Y)有这个嵌入式的逻辑。

You must unbox value-types (such as int/double) correctly. Or use Convert.ToInt32(y) which has the logic for this embedded.

在第二个例子中,这是一个转换(不是拆箱,而不是垂头丧气)。转换是指无论是在语言规范(如在这种情况下)或者通过自定义静态的运营商。

In the second example, this is a conversion (not an unbox, and not a downcast). Conversions are defined either in the language spec (like in this case) or via custom static operators.

所不同的是对象。箱变的所有

这篇关于为什么垂头丧气在运行时出现故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆