c# - 在 C# 中将数字字符串转换为枚举

标签 c# enums

最近我发现任何只包含数字字符的字符串都可以在 C# 中转换为枚举。例如,假设有一个枚举定义如下:

public enum TestEnum
{
    One = 1,
    Two = 2,
    Three = 3
};

我可以将一些随机数字字符串转换为 TestEnum

TestEnum testEnum = (TestEnum)Enum.Parse(typeof(TestEnum), "4");
Console.WriteLine(testEnum);

值“4”当然不会映射到定义的 TestEnum 值之一,输出将只是 4,但是不会有错误,所以这种转换是合法的。

另一方面,如果我尝试检查此值是否在 TestEnum 中定义:

Console.WriteLine(Enum.IsDefined(typeof(TestEnum), "4"));

我会在输出中收到 False

这对我来说似乎有点奇怪,考虑到以下非数字字符串的转换,例如

(TestEnum)Enum.Parse(typeof(TestEnum), "Test")

将抛出 System.ArgumentException

我对这种行为感到困惑。是故意这样设计的还是巧合?

最佳答案

Was it intentionally designed this way or is this just a coincidence?

我不确定我是否理解您的问题。 The documentation对我来说似乎完全清楚:

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

(强调我的)

它还说:

If value is the string representation of an integer that does not represent an underlying value of the enumType enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of enumType

显然这是有意为之的行为,而不仅仅是巧合。

请注意,您始终可以将 enum 的基础类型(在本例中为 int)的任何值转换为 enum 类型本身。 enum 类型功能不强制 enum 的值对应于命名值。因此解析行为与 enum 类型的编译时行为完全一致。

我想有人可能会争论 enum 类型是否应该允许使用未命名的值。但是,鉴于 enum 类型的特性之一是允许基于标志的枚举,无论它们是否具有 [Flags] 属性,并且假设它会必须命名在 enum 类型中定义的每个标志的每个组合是不方便的(至少可以说),他们继续并允许所有类型的未命名值似乎是合理的 enum 类型。

关于c# - 在 C# 中将数字字符串转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55316183/

相关文章:

c# - Entity Framework Core 获取没有相关实体的实体

enums - 如何使 CRMSvcUtil.exe 生成不重复、无错误的早期绑定(bind)选项集?

c# - 从 DataTable 和枚举填充 DataGridViewComboBoxColumn

c++ - 用枚举填充 QMenu

java - 当在运行时获取枚举时,使用枚举类中的方法

c# - 默认参数 PageSize A4 C# 使用 itextsharp

c# - 将日期时间值更新到具有奇怪格式的数据库中显示不正确的日期

c# - 无法使用 C# HttpClient 上传文件,Postman 工作正常

c# - Avalonedit 如何以编程方式更改文本背景

c++ - C++ 中的全局枚举