我想使用 switch 语句来避免许多 if。所以我这样做了:
public enum Protocol
{
Http,
Ftp
}
string strProtocolType = GetProtocolTypeFromDB();
switch (strProtocolType)
{
case Protocol.Http:
{
break;
}
case Protocol.Ftp:
{
break;
}
}
但是我在比较枚举和字符串时遇到了问题。因此,如果我添加了 Protocol.Http.ToString() ,则会出现另一个错误,因为它只允许进行 CONSTANT 评估。如果我把它改成这个
switch (Enum.Parse(typeof(Protocol), strProtocolType))
这也不可能。那么,在我的案例中是否可以使用 switch 语句?
最佳答案
您需要将 Enum.Parse
结果转换为 Protocol
以使其工作。
switch ((Protocol)Enum.Parse(typeof(Protocol), strProtocolType))
关于c# - 如何在枚举 C# 中使用 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19958080/