编辑:底部的评论.还有,这个.
这就是让我感到困惑的一点.我的理解是,如果我有这样的枚举......
enum Animal
{
Dog,
Cat
}
Run Code Online (Sandbox Code Playgroud)
...我基本上完成的是定义了一个用两个定义的值调用的值类型Animal,Dog和Cat.这种类型派生自引用类型 System.Enum(值类型通常不能执行的操作 - 至少不在C#中 - 但在这种情况下是允许的),并且具有用于在int值之间来回转换的工具.
如果我刚刚描述上面的枚举类型的方式是真的,那么我希望以下代码抛出InvalidCastException:
public class Program
{
public static void Main(string[] args)
{
// Box it.
object animal = Animal.Dog;
// Unbox it. How are these both successful?
int i = (int)animal;
Enum e = (Enum)animal;
// Prints "0".
Console.WriteLine(i);
// Prints "Dog".
Console.WriteLine(e);
}
}
Run Code Online (Sandbox Code Playgroud)
通常,您不能将值类型System.Object从其确切类型以外的任何其他方式取消装箱.那以上怎么可能呢?这是因为如果该 …
考虑以下::
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.
Run Code Online (Sandbox Code Playgroud)
2件事::
StringComparison?我想这是因为它的底层类型是,Int32但我仍然觉得它很奇怪.nullableEnum值为null?据我所知,唯一有效的拆箱是从盒装值类型到它的类型或可空类型.如果int可以取消装箱Enum,那么为什么不能同样适用于可空值?同样,如果不是5我装盒StringComparison.OrdinalIgnoreCase,那nullableInt将是null,但nullableEnum不会.