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

Bro*_*ato 3 c#

我发现了一个非常基本的代码,如下所述,我无法在c#windows Forms解决方案中使用它.我收到了错误:

  • '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)
    {
        ...
    }
    
    Run Code Online (Sandbox Code Playgroud)

我不明白问题出在哪里.错误都Enum.TryParse在线上.任何的想法?

谢谢.

Dar*_*rov 13

从文档中可以看出,Enum.TryParse<TEnum>是一个返回布尔属性的泛型方法.您使用不正确.它使用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
}
Run Code Online (Sandbox Code Playgroud)