c# - Enum.TryParse 对任何数值返回 true

标签 c# validation enums tryparse

我遇到了使用 Enum.TryParse 时未预料到的行为。

如果我有一个枚举:

public enum MyEnum
{
  ValueA,
  ValueB,
  ValueC
}

然后我将数值(作为字符串)传递给 Enum.TryParse,例如:

MyEnum outputEnum;
bool result = Enum.TryParse("1234", out outputEnum);

尽管字符串“1234”不是一个可能的值,结果将返回为真,我的 outputEnum 的值为 1234。

有什么办法可以避免这种行为?我正在尝试编写一个将任意字符串输入作为枚举处理的函数,这在我的错误输入检测中引发了一些麻烦。

最佳答案

此行为是设计使然。

documentation说:

. If value is the string representation of an integer that does not represent an underlying value of the TEnum 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 TEnum.

调用 Enum.IsDefined 以验证您解析的值确实存在于这个特定的 enum 中。

如果您正在处理 [Flags] 枚举(位掩码),它会变得更加复杂。

关于c# - Enum.TryParse 对任何数值返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6741649/

相关文章:

c# - 无法将类型 'void' 隐式转换为 'System.Threading.Tasks.Task'

javascript - PHP laravel 5 以输入名称作为键的验证错误

java - 为什么我不能在 Kotlin 中访问父类(super class)的枚举?

enums - 使用关联类型时密封类与枚举

c# - 如何使用 itextsharp 读取 marge fillable pdf 数据

c# - 用于 C# 的 Gedcom 阅读器

c# - 如何知道线程池中的线程挂起/卡住

php - 使用 PHP 和 javascript 进行 HTML 表单验证的简单方法

validation - Codeigniter:如何构建使用表单验证和重新填充的编辑表单?

c - C 语言中的有限状态机