如何与枚举在C#中比较字符串 [英] how to compare string with enum in C#

查看:249
本文介绍了如何与枚举在C#中比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string strName = "John";
public enum Name { John,Peter }

private void DoSomething(string myname)
{
case1:
     if(myname.Equals(Name.John) //returns false
     {

     }

case2:
     if(myname == Name.John) //compilation error
     {

     }

case3:
     if(myname.Equals(Name.John.ToString()) //returns true (correct comparision)
     {

     }
}

当我使用 .Equals 是参考比较,当我使用 == 表示值进行比较。

when I use .Equals it is reference compare and when I use == it means value compare.

有没有更好的code,而不是枚举值转换为的ToString()作比较?因为它破坏了价值枚举类型的目的,并可以,的ToString()的枚举是pcated ??德$ P $

Is there a better code instead of converting the enum value to ToString() for comparison? because it destroys the purpose of value type enum and also, ToString() on enum is deprecated??

推荐答案

您可以使用 Enum.TryParse() 方法将字符串转换为等效的枚举值(假设它存在):

You can use the Enum.TryParse() method to convert a string to the equivalent enumerated value (assuming it exists):

Name myName;
if (Enum.TryParse(nameString, out myName))
{
    switch (myName) { case John: ... }
}

这篇关于如何与枚举在C#中比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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