why downcast fails at runtime

后端 未结 1 1194
既然无缘
既然无缘 2021-01-20 02:06

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         


        
相关标签:
1条回答
  • 2021-01-20 02:21

    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.

    0 讨论(0)
提交回复
热议问题