Using enum as generic type parameter in C# [duplicate]
Possible Duplicate:
Enum type constraints in C#
Is it possible to use enum
types as a generic 开发者_Python百科paramter by using its wrapper class Enum
?
I have different enums:
enum errors1 { E1, E3, E8 };
enum errors2 { E0, E2, E9 };
enum errors3 { E7, E4, E5 };
With the following class declaration I thought I could achieve it:
public class MyErrors<T> where T : Enum
{
T enumeration;
public T getEnumeration()
{
return enumeration;
}
static void Main(string[] args)
{
Program<error1> p = new Program<error1>();
p.getEnumeration().E1 // this call does NOT work
}
However, since the general type is Enum
I can only access the member and methods of the Enum
class. So is it possible to implement it the way I meant to or what other approach should I use?
No, it's not possible unfortunately. The best you can do is use where T : struct, IComparable, IConvertible, IFormattable
(which of course is not the same). The interface restrictions are derived from the implementation of System.Enum
.
Apart from that, you can check if typeof(T).IsEnum
, which can detect the problem at runtime and presumably throw an exception. But there is no way to enforce this restriction at compile time.
This is not doable at the language level in C#, but it's supported by the underlying CLR. You can use Jon Skeet's Unconstrained Melody, which will transform the generated binary to one with the actual enum generic constraint.
精彩评论