C#: Enums in Interfaces

前端 未结 5 647
有刺的猬
有刺的猬 2021-02-07 05:58

I\'ve seen a couple similar threads to this question, but none of them really answer the question I want to ask.

For starters, unfortunately I\'m working with existing A

5条回答
  •  青春惊慌失措
    2021-02-07 07:02

    As Jon Skeet mentioned, the base IL supports constraining generics to be enums, however C# does not allow you to take advantage of it.

    F# does allow this sort of constraint, however. Further, if the interface is defined in F#, the constraint will be enforced in C# code that implements the interface. If you're willing to mix languages in your solution, something like this should work just fine:

    type IError<'T when 'T :> System.Enum and 'T : struct> =
        abstract member Error : 'T
        abstract member Description : string
    

    If you put this in an F# project and reference it from your C# project, your C# code that implements the interface will cause a C# compiler error on any attempt to use it with a non-enum type.

提交回复
热议问题