枚举参数的扩展方法必须限制为结构

Extension Method on enum parameter must be constrained to a struct

我看过一些代码

它被设计用来获取一个枚举值并获取描述。相关部分是:

public static string GetDescription<T>(this T enumerationValue) where T : struct

我正在使用相同的代码,但令我困惑的是我无法更改约束

public static string GetDescription<T>(this T enumerationValue) where T : enum

public static string GetDescription<T>(this T enumerationValue) where T : class

2 个问题由此产生。

第一个是当我使用enum作为约束参数时。这应该constrain the generic parameter to an enum。如果是这样,为什么我不能输入像

这样的代码
var a = "hello world";

函数内。这与参数无关...

我的第二个问题是,当我将约束更改为 class 时,上面的代码片段 (var a = "hello world";) 工作正常,但是当我调用该函数时,我收到错误消息

'Enum.Result' must be a reference type in order to use it as parameter 'T' in the generic type or method 'GetDescription<T>(T)'

Enum.Result must be a reference type...我以为class是引用类型...

为什么 中的示例仅适用于 struct

为什么 T : class 不起作用的问题是因为枚举总是一个结构。所以你看错了。你写:

Enum.Result must be a reference type... I thought a class was a reference type...

你说得对 class 是引用类型。但是 Enum.Result 不是 class。这是一个如上所述的结构。您的约束 T : class 只接受引用类型。

此外,如果将约束更改为 T : enum,则不能在函数中键入 var a = "hello world";,因为此约束无效。因此,在修复约束之前,您将无法在方法中编写任何有效代码。

查看 msdn 了解哪些约束是可能的。

正如评论所说,枚举不是 class。 但是,枚举是。它只是一个特殊的类型,如果你试图像那样限制类型,它不会让你:

public static string GetDescription<T>(this T enumerationValue) where T : Enum

Constraint cannot be special class 'Enum'

您链接的问题中的现有代码是您可以做的最好的,但如果您需要更多信息,请参阅此处:Create Generic method constraining T to an Enum

关于你问题的第二部分,关于将其限制为 'class',那一定是有其他事情发生了。

编辑 - 我很笨 - Sebi 说的。 :)

您的代码片段或您链接到的答案中都没有 Enum.Result,因此我认为我们需要查看更多您的代码才能回答该问题。