Enum.TryParse奇怪的行为 [英] Enum.TryParse strange behaviour

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

问题描述

为什么该测试通过?TestEnum不包含和值为"5"的选项.因此,该测试应该会失败,但不会失败.

Why does this test pass? TestEnum doesn't contain and option with value "5". So this test should fail, but it doesn't.

        private enum TestEnum
        {
            FirstOption = 2,
            SecontOption = 3
        }

        [Test]
        public void EnumTryParseIntValue()
        {
            TestEnum enumValue;

            bool result = Enum.TryParse<TestEnum>(5.ToString(), out enumValue);

            Assert.IsTrue(result);
        }

推荐答案

Enum.TryParse方法(字符串,TEnum)

如果value是与命名常量不对应的名称TEnum,该方法返回false.如果value是字符串表示形式不代表TEnum基础值的整数枚举,该方法返回一个枚举成员,该枚举成员的基础value是将值转换为整数类型的值.如果这种行为是不可取的是,调用IsDefined方法以确保特定的整数的字符串表示形式实际上是TEnum的成员.

If value is a name that does not correspond to a named constant of TEnum, the method returns false. 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.

返回其基础值为转换为整数类型的值的枚举成员"
如果不存在该值,则返回整数.我不认为让5成为枚举成员",但这就是它的工作原理.如果您解析2,则将获得FirstOption.

"Returns an enumeration member whose underlying value is value converted to an integral type"
If the value is not present you get back the integer. I don't consider getting back 5 to be an "enumeration member" but that is how it works. If you parse 2 you get FirstOption.

if (Enum.IsDefined(typeof(TestEnum), 5.ToString()))
{
    result = Enum.TryParse<TestEnum>(5.ToString(), out enumValue);
    Debug.WriteLine(result);
    if (result)
    {
        Debug.WriteLine(enumValue.ToString());
    }
}

这篇关于Enum.TryParse奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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