4

我找到了一个非常基本的代码,如下所述,我无法让它在我的 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)
    {
        ...
    }
    

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

谢谢。

4

3 回答 3

15

正如您从文档中看到的那样,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
}
于 2013-07-01T08:59:46.220 回答
4

首先要注意的是TryParse返回一个布尔值而不是Type你的枚举。

out参数必须指向一个变量,该变量Typeenum.

于 2013-07-01T09:00:53.297 回答
2

我认为您应该使用 Enum.Parse:

 PetType pet = (PetType)Enum.Parse(typeof(PetType), value);

TryParse 仅在解析成功时返回 true,否则返回 false。

于 2013-07-01T09:06:21.267 回答