我有一个带有通用方法的类:
public record OperationCollectionGeneric<OPERATIONTYPE> where OPERATIONTYPE: notnull, Enum
{
public OPERATIONTYPE Group { get; }
public OperationCollectionGeneric(string part1, string? part2 = null, string? part3 = null)
{
Group = Enum.Parse<OPERATIONTYPE>(part1, true);
}
Enum.Parse()
方法出现以下错误:
Error CS0453 The type 'OPERATIONTYPE' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.Parse(ReadOnlySpan, bool)'
如何传递确保 OPERATIONTYPE 参数为 Enum 类型
我尝试使用 where
键设置 OPERATIONTYPE
的枚举类型,但它不起作用。
最佳答案
Enum.Parse
仅限于struct
,因此更改通用约束以匹配它:
public record OperationCollectionGeneric<OPERATIONTYPE> where OPERATIONTYPE : struct, Enum
关于c# - 如何将泛型类型作为参数传递给 Enum.Parse(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74601618/