c# - 如何将泛型类型作为参数传递给 Enum.Parse()

标签 c# .net .net-core

我有一个带有通用方法的类:

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/

相关文章:

c# - 需要参数 '@ID' ,但未提供?

c# - .NET Core 中是否有 HtmlTableRow 的模拟

c# - 如何使用 Moq 模拟 IMongoCollection.Find

c# - 使用 System.Net.Sockets.Socket.AcceptAsync 模型时发生堆栈溢出

c# - 使用 Azure 的 '/' 应用程序中的服务器错误

C# 正则表达式,通过引用字符串提取字符串

c# - 使用此字符串填充 DateTime 对象 03-06-2012 08 :00 am

asp.net - 将 mvc 应用程序发布到 Web 服务器后无法生成 SSPI 上下文异常

.net - 如何在 Visual Web Developer 2008 Express Edition 和 ASP.NET MVC 中编辑和继续?

visual-studio - Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking.UvException : 'Error -4092 EACCES permission denied'