我找到了如下所述的非常基本的代码,但我无法在我的 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/