C# 7.3 Enum constraint: Why can't I use the enum keyword?

后端 未结 1 1887
名媛妹妹
名媛妹妹 2020-12-31 01:05

To constrain a generic type parameter to be of an enum type, I previously constrained them like this, which was the best I could go for constraining type T for enums in pre-

相关标签:
1条回答
  • 2020-12-31 01:20

    The struct constraint on generics doesn't map to an actual type (though it could, in theory, map to ValueType). Similarly, enum doesn't cleanly map to actual types the way string, int, or long do, it sets up special syntax for creating a class of symbolic constants that map to integer values; hence public enum Stuff instead of public class Stuff : Enum. Note that had the latter been implemented instead, it would be more subtle since it would change syntax based on inherited type, instead of changing syntax based on a non-class keyword.

    So, in conclusion, yes, where T : enum is not meant to work because enum is a keyword, not a type alias. If you really want to see it work because enum at least smells like a type alias in context like these, go request it!

    EDIT: For some historical reference, here's a question from 2008 indicating that Enum was not a valid constraint, since it's a special class.

    0 讨论(0)
提交回复
热议问题