c# - Enum.TryParse 的非常基本的使用不起作用

标签 c#

我找到了如下所述的非常基本的代码,但我无法在我的 c# Windows 窗体解决方案中使用它。我得到了错误:

  • “System.Enum.TryParse(string, out string)”的最佳重载方法匹配有一些无效参数

  • 参数 1:无法从“System.Type”转换为“string”

    public enum PetType
    {
        None,
        Cat = 1,
        Dog = 2
    }
    
    string value = "Dog";
    PetType pet = (PetType)Enum.TryParse(typeof(PetType), value);
    
    if (pet == PetType.Dog)
    {
        ...
    }
    

我不明白问题出在哪里。错误都在 Enum.TryParse 行。有什么想法吗?

谢谢。

最佳答案

从文档中可以看出, Enum.TryParse<TEnum> 是返回 bool 属性的通用方法。您使用不当。它使用 out存储结果的参数:

string value = "Dog";
PetType pet;
if (Enum.TryParse<PetType>(value, out pet))
{
    if (pet == PetType.Dog)
    {
        ...
    }
}
else
{
    // Show an error message to the user telling him that the value string
    // couldn't be parsed back to the PetType enum
}

关于c# - Enum.TryParse 的非常基本的使用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17400617/

相关文章:

c# - 没有空格的任何字符的正则表达式

c# - wpf 用户控件在应用程序内的多个位置具有公开命令

c# - 使用命名互斥体

c# - 未知的网络方法。参数名称: methodName in web services

c# - iTextSharp 5 润色字符

c# - 回发后javascript更改清除

c# - EPPlus - 行超出范围异常

c# - 使用 AppDomain.CreateInstanceAndUnwrap 方法时为 "Unable to cast transparent proxy to type"

c# - 在 c# 中使用 file.move 时文件锁定...如何停止或修复此问题

c# - WMI - IIS 7 - 检索所有网站绑定(bind)