how to compare string with enum in C#

前端 未结 6 1822
自闭症患者
自闭症患者 2020-12-03 13:07
string strName = \"John\";
public enum Name { John,Peter }

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


        
相关标签:
6条回答
  • 2020-12-03 13:53

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

    0 讨论(0)
  • 2020-12-03 13:55

    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

    0 讨论(0)
  • 2020-12-03 13:59

    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: ...
        }
    
    0 讨论(0)
  • 2020-12-03 14:03

    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: ... }
    }
    
    0 讨论(0)
  • 2020-12-03 14:03

    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 */
    }
    
    0 讨论(0)
  • 2020-12-03 14:03

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

    if(myname.Equals(Enum.Parse(Name.John)) //returns false
     {
    
     }
    
    0 讨论(0)
提交回复
热议问题