为什么unboxing枚举会产生奇怪的结果? [英] Why does unboxing enums yield odd results?

查看:123
本文介绍了为什么unboxing枚举会产生奇怪的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下::

Object box = 5;
int @int = (int)box;  // int = 5
int? nullableInt = box as int?; // nullableInt = 5;
StringComparison @enum = (StringComparison)box; // enum = OrdinalIgnoreCase
StringComparison? nullableEnum = box as StringComparison?; // nullableEnum = null.

2件事:


  1. 为什么我可以取消收件到 StringComparison ?我猜这是因为它的底层类型是 Int32 ,但我仍然觉得很奇怪。

  2. 为什么 nullableEnum 的值为null?

  1. Why can I unbox to StringComparison? I guess this is because it's underlying type is Int32 but I still find it odd.
  2. Why does nullableEnum have a value of null?

据了解,唯一有效的取消装箱是从盒装值类型到它的类型或可空类型。如果 int 可以取消收件箱到枚举,那么为什么不相同的可空值呢?同样地,如果我取而代之的是我装箱 StringComparison.OrdinalIgnoreCase ,那将是 nullableInt 将为null,但 nullableEnum 不会。

As I understand the only valid unboxing is from a boxed value type is to it's type or to a nullable type. If int can unbox to Enum, then why doesn't the same hold true for the nullable values? Similarly, if Instead of 5 I boxed StringComparison.OrdinalIgnoreCase, it would be that nullableInt would be null, but nullableEnum would not be.

推荐答案

严格来说,我认为这是一个<由于C#规范表示

Strictly speaking I think it's a bug in implementation detail of the runtime, since the C# spec says


将实现细节如果源操作数为null,或者将对象实例解包到可空类型的底层类型的包装结果,则-type将生成可空类型的空值。否则

Unboxing to a nullable-type produces the null value of the nullable-type if the source operand is null, or the wrapped result of unboxing the object instance to the underlying type of the nullable-type otherwise.

也就是说,如果拆箱到StringComparison工作,然后取消装箱到Nullable< StringComparison>也应该工作。两者都应该工作还是两者都应该失败有点不清楚。该规范表示

That is, if unboxing to StringComparison works, then unboxing to Nullable<StringComparison> should work too. It's a little unclear whether both should work or both should fail. The spec says that


对于在运行时取消成功转换给给定的非可空值类型,源操作数必须是对该非可空值类型的盒装值的引用。

For an unboxing conversion to a given non-nullable-value-type to succeed at run-time, the value of the source operand must be a reference to a boxed value of that non-nullable-value-type.

您必须决定是否boxed int被认为是StringComparison类型的Boxed值,因为StringComparison的底层类型是int。该规范继续说,如果框包含不兼容的对象,则抛出InvalidCastException。由于您可以将堆中的四个字节安全地复制到StringComparison变量中,因此您可以使用StringComparison确定兼容。

You have to decide whether a boxed int is a considered to be a boxed value of type StringComparison because the underlying type of StringComparison is int. The spec goes on to say that an InvalidCastException is thrown if the box contains an "incompatible object". An int is certainly "compatible" with StringComparison, because you can safely copy the four bytes from the heap into your StringComparison variable.

这篇关于为什么unboxing枚举会产生奇怪的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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