how to compare string with enum in C#

前端 未结 6 1832
自闭症患者
自闭症患者 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 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: ... }
    }
    

提交回复
热议问题