简体   繁体   English

C#中的枚举的Tryparse和IsDefined

[英]Tryparse and IsDefined for Enum in C#

All, I have to do is: 所有,我要做的是:

Find out whether a string is a valid Enum element and if so, return status. 找出字符串是否是有效的Enum元素,如果是,则返回状态。

something like, If I have an enum say Enum_Test which in turn consists of red, blue , green as its value. 类似的东西,如果我有一个枚举说Enum_Test,它又由红色,蓝色,绿色组成。

Now, if blue is the element to be verified, I use something like 现在,如果蓝色是要验证的元素,我会使用类似的东西

Enum_Test evalue;
if(Enum.TryParse(string_Verify, true, out evalue))  
{
        return true;
}

Or otherwise I have an another option, 或者我有另一种选择,

if( Enum.IsDefined(typeof(Enum_Test), string_Verify))
{
        return true;
}

What is the advantages and pit falls in the above methods ? 上述方法的优点和缺点是什么?

Advantage of the first method : It's case insensitive: If you get blue , and there's an enumeration member Blue , all will be fine. 第一种方法的优点 :它不区分大小写:如果你得到blue ,并且有一个枚举成员Blue ,一切都会好的。

Advantage of the second method : It's self-documenting: You don't really want to parse , you want to check whether there is an enum value defined with a given name. 第二种方法的优点 :它是自我记录的:你真的不想解析 ,你想检查是否有一个用给定名称定义的枚举值。 So, in the second case, the name of the method more closely matches your intent. 因此,在第二种情况下,方法的名称更符合您的意图。

That said, if you want both advantages, use the first method and encapsulate it into a well-named method (eg IsEnumDefinedIgnoreCase ). 也就是说,如果你想要两个优点,请使用第一个方法并将其封装到一个命名良好的方法中(例如IsEnumDefinedIgnoreCase )。

另外,请注意,如果您传递一个包含数字的字符串,例如“123”,TryParse方法将返回true。

In first case if your parsing is successful then you will get the enum value in evalue . 在第一种情况下,如果解析成功,那么您将获得evalue的枚举值。 You are also passing true for ignore case parameter, so the comparison will ignore the case of the string. 您还将忽略case参数传递true ,因此比较将忽略字符串的大小写。 The way you have it now, it would return true in success and discard the value in evalue . 你现在拥有它的方式,它将成功返回true并丢弃evalue的值。

In 2nd code you are only checking if the enum is defined or not. 在第二个代码中,您只检查是否定义了枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM