为什么不能做这个铸造
问题描述:
enum Gender
{
male, female
}
class Program
{
static void Main(string[] args)
{
Gender M = Gender.male;
M = 0;
//
Gender F = Gender.female;
F = 1; // this wrong statement , must be implicitly cast
}
}
为什么我们可以隐式转换为(零),另一个值必须是显式转换?
why we can just do implicitly cast for (zero), and another value must be explicit casting ??
答
因为任何值类型的默认值都是零 - 并且枚举是值类型。
所以你总是可以为它指定一个零(或者它没有一个默认值,这可能是愚蠢的)但是你不能给它分配任何其他整数值而不用它到枚举(确保你的意思是这样做,因为它可以生成不属于枚举的值,特别是当你没有指定枚举值时,你不会)
Because the default value for any value type is zero - and an enum is a value type.
So you can always assign a zero to it (or it couldn''t have a default value, which would be silly) but you can''t assign any other integer value to it without casting it to an enum (to be sure you meant to do that, as it could generate values which are not part of the enumeration, particularly when you don''t specify enum values, as you don''t)