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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用.Equals
它时是参考比较,当我使用==
它时意味着值比较.
是否有更好的代码而不是将枚举值转换ToString()
为比较?因为它破坏了值类型枚举的目的而且,ToString()
在枚举上被弃用了?
dle*_*lev 57
您可以使用该Enum.TryParse()
方法将字符串转换为等效的枚举值(假设它存在):
Name myName;
if (Enum.TryParse(nameString, out myName))
{
switch (myName) { case John: ... }
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*ing 26
您可以解析字符串值并进行枚举比较.
Enum.TryParse:请参阅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 */
}
Run Code Online (Sandbox Code Playgroud)
如果您只是比较单个值:
Name result;
if (Enum.TryParse(myname, out result) && result == Name.John)
{
/* do 'John' logic */
}
else
{
/* do non-'John' logic */
}
Run Code Online (Sandbox Code Playgroud)
如果使用.NET4或更高版本,则可以使用Enum.TryParse
。并Enum.Parse
适用于.NET2和更高版本
// .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: ...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
63370 次 |
最近记录: |