How to constraint a generic to be of type enum?
-
17-04-2021 - |
Вопрос
Consider the following code:
class Base<T>
{
//Base members
}
I want the generic T to be an enum (using constraints if possible). How can I do this in C#?
EDIT:
Using code contracts -introduced by Akash Kava- also seems like a nice way. I managed to get it to produce a run time error which is useless. Here's the code I tried. It should be possible to generate a compile time warning but I can't get it to work.
Решение
This is supported at the IL level but not in C#. You may take a look at unconstrained melody written by Jon Skeet which allows you to achieve that. And here's the corresponding blog post where he explains in details.
Другие советы
.NET 4.0 onwards you can create warnings by using Code Contracts, http://msdn.microsoft.com/en-us/devlabs/dd491992, this will let you check some preconditions and display warnings to developer.