why downcast fails at runtime

陌路散爱 提交于 2019-12-20 02:52:05

问题


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

case 1:

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

case 2:

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

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


回答1:


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.

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.

The difference is object. The box changes everything.



来源:https://stackoverflow.com/questions/1812172/why-downcast-fails-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!