简体   繁体   English

铸造对象到十进制c尖锐的奇怪行为

[英]strange behavior of cast object to decimal c sharp

I ran with strangeness: 我陌生地奔跑:

var k = (decimal?)(int?)1; //valid cast
var p = (decimal?)(int?)(object)(int?)1; //valid cast
var l = (decimal?)(object)(int?)1; //Specified cast is not valid

Can someone explain why this happens? 有人可以解释为什么会这样吗?

The first cast is: 第一个演员是:

  • Convert int to int? int转换为int?
  • Convert int? 转换int? to decimal? decimal?

Both conversions are valid. 两次转换都有效。

The second case is: 第二种情况是:

  • Convert int to int? int转换为int?
  • Box the int? 盒子int? (which ends up as a boxed int ) (最终作为盒装int
  • Unbox the object to int? 将对象解包为int?
  • Convert int? 转换int? to decimal? decimal?

All of these conversions are valid. 所有这些转换都是有效的。

The third case is: 第三种情况是:

  • Convert int to int? int转换为int?
  • Box the int? 盒子int? (which ends up as a boxed int ) (最终作为盒装int
  • Unbox the object to decimal? 将对象解包为decimal?

The last conversion here is invalid - you can only unbox to the same value type or its nullable equivalent. 此处的最后一次转换无效 - 您只能取消装入相同的值类型或其可空等效值。 (Actually the CLR is somewhat more forgiving than this, but that's not relevant in this case.) (实际上CLR比这更宽容一些,但在这种情况下这并不相关。)

The conversion to int? 转换为int? in each case is actually irrelevant. 在每种情况下实际上是无关紧要的。 The unboxing to a nullable type is somewhat irrelevant too, in that unboxing to a nullable type is like unboxing to a non-nullable type, except that a null reference is unboxed to a null value. 对可空类型的拆箱也有些不相关,因为拆箱到可空类型就像拆箱到非可空类型一样,除了将空引用解包为空值。 Given that there are no null values here, your final example is equivalent to: 鉴于此处没有空值,您的最​​终示例相当于:

object o = 1; // Boxing
decimal d = (decimal) o; // Unboxing, but to the wrong type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM