C#: Enums in Interfaces

前端 未结 5 779
有刺的猬
有刺的猬 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 06:44

    Yes, I've run up against this. Not in this particular situation, but in other Stack Overflow questions, like this one. (I'm not voting to close this one as a duplicate, as it's slightly different.)

    It is possible to express your generic interface - just not in C#. You can do it in IL with no problems. I'm hoping the limitation may be removed in C# 5. The C# compiler actually handles the constraint perfectly correctly, as far as I've seen.

    If you really want to go for this as an option, you could use code similar to that in Unconstrained Melody, a library I've got which exposes various methods with this hard-to-produce constraint. It uses IL rewriting, effectively - it's crude, but it works for UM and would probably work for you too. You'd probably want to put the interface into a separate assembly though, which would be somewhat awkward.

    Of course, you could make your interface just have T : struct instead... it wouldn't be ideal, but it would at least constrain the type somewhat. So long as you could make sure it wasn't being abused, that would work reasonably well.

提交回复
热议问题