C#枚举是否类型安全? [英] Are C# enums typesafe?

查看:81
本文介绍了C#枚举是否类型安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#枚举类型是否安全?

Are C# enums typesafe?

如果不是什么意思?

推荐答案

给出一个稍微不同的答案,而从铸造角度来看,这些值是类型安全的,它们仍然未被选中一旦他们被投了 - 即

To give a slightly different answer... while the values are type-safe from the casting perspective, they are still unchecked once they have been cast - i.e.

enum Foo { A = 1, B = 2, C = 3 }    
static void Main()
{
    Foo foo = (Foo)500; // works fine
    Console.WriteLine(foo); // also fine - shows 500
}

因此,您应该注意检查值 - 例如在开关中的默认值中引发异常。

For this reason, you should take care to check the values - for example with a default in a switch that throws an exception.

您还可以通过以下方式检查(对于非 [Flags] 值):

bool isValid = Enum.IsDefined(typeof(Foo), foo);

这篇关于C#枚举是否类型安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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