how to compare string with enum in C#

馋奶兔 提交于 2019-12-17 16:24:05

问题


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)
     {

     }
}

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

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??


回答1:


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: ... }
}



回答2:


You can parse the string value and do enum comparisons.

Enum.TryParse: See http://msdn.microsoft.com/en-us/library/dd783499.aspx

Name result;
if (Enum.TryParse(myname, out result))
{
    switch (result)
    {
        case Name.John:
            /* do 'John' logic */
            break;
        default:
            /* unexpected/unspecialized enum value, do general logic */
            break;
    }
}
else 
{
    /* invalid enum value, handle */
}

If you are just comparing a single value:

Name result;
if (Enum.TryParse(myname, out result) && result == Name.John)
{
     /* do 'John' logic */
}
else 
{
    /* do non-'John' logic */
}



回答3:


If you using .NET4 or later you can use Enum.TryParse. and Enum.Parse is available for .NET2 and later

// .NET2 and later
try
{
    switch (Enum.Parse(typeof(Names), myName))
    {
        case John: ... 
        case Peter: ...
    }
}

// .NET4 and later
Name name;
if (Enum.TryParse(myName, out name))
    switch (name)
    {
        case John: ... 
        case Peter: ...
    }



回答4:


One solution could be to get the type of the enum, and then the types name.

myname.Equals(Enum.GetName(typeof(Name)))

http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx




回答5:


For some reason, the given solutions didn't workout for me. I had to do in a slighly different way:

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

Hope it helps someone :)




回答6:


I think you're looking for the Enum.Parse() method.

if(myname.Equals(Enum.Parse(Name.John)) //returns false
 {

 }


来源:https://stackoverflow.com/questions/11508865/how-to-compare-string-with-enum-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!