Enum.TryParse 对任何数值返回 true [英] Enum.TryParse returns true for any numeric values

查看:22
本文介绍了Enum.TryParse 对任何数值返回 true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Enum.TryParse 时遇到了我没想到的行为.

I'm running into a behavior I wasn't expecting when using Enum.TryParse.

如果我有一个枚举:

public enum MyEnum
{
  ValueA,
  ValueB,
  ValueC
}

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

And then I pass a numeric value (as a string) into Enum.TryParse, like:

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

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

Despite the string "1234" not being a possible value, result will come back as true, and my outputEnum will have a value of 1234.

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

Is there a way I can avoid this sort of behavior? I'm trying to write a function which will process arbitrary string input as an enum, and this has thrown a bit of a monkeywrench in my bad-input detection.

推荐答案

这种行为是设计使然.

文档 说:

.如果 value 是不表示 TEnum 枚举的基础值的整数的字符串表示形式,则该方法返回一个枚举成员,其基础值是转换为整数类型的值.如果此行为不受欢迎,请调用 IsDefined 方法以确保整数的特定字符串表示实际上是 TEnum 的成员.

. 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 中.

Call Enum.IsDefined to veryify that the value you parsed actually exists in this particular enum.

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

If you're dealing with [Flags] enums (bitmasks), it'll get more complicated.

这篇关于Enum.TryParse 对任何数值返回 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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