Enum.TryParse 在泛型中不被接受,仅限于 Enum

Mog*_*og0 1 c# generics enums

我想我可能在做一些愚蠢的事情,但我正在尝试编写一个通用函数,该函数接受 astring并将其转换为 an enum(然后做了一些我为了简洁而跳过的其他东西)。问题是,它抱怨Enum.TryParse需要一个不可为空的类型,它抱怨 T 是可以为空的;看似可以System.Enum为空,但实际枚举不可为空。是我在这里做错了什么还是有办法解决这个问题。

private T GetEnumFilter<T>(string strValue) where T : Enum
{
     return Enum.TryParse(strValue, out T value) ? value : throw new Exception("Invalid value");
}
Run Code Online (Sandbox Code Playgroud)

我看过这个/sf/answers/566075191/答案和dotnet 样本中的样本,但看不出我做错了什么。

Jon*_*eet 5

看似 System.Enum 可以为空,但实际枚举不可为空。

是的,就像System.ValueType引用类型一样,但值类型本身不是。

你只需要添加一个struct约束:

private T GetEnumFilter<T>(string value) where T : struct, Enum
Run Code Online (Sandbox Code Playgroud)

这编译,例如:

private static T GetEnumFilter<T>(string value) where T : struct, Enum =>
    Enum.TryParse(value, out T result) ? result : throw new Exception("Invalid value");
Run Code Online (Sandbox Code Playgroud)