Restricting generic function to only work on Enums [duplicate]
I have the following generic function:
public SomeType SomeFunction<T>(T value)
{
}
I would now like to restrict this generic function to work only with Enum
s so I tried the following开发者_开发百科:
public SomeType SomeFunction<T>(T value) where T : System.Enum
{
}
But this resulted in:
error CS0702: Constraint cannot be special class 'System.Enum'
Is there a work around and out of curiosity does anyone know the reason why this type of constraint isn't allowed?
You can't. You can restrict it to value types, but that's all. Restricting it to enums can only be done using runtime checking:
public SomeType SomeFunction<T>(T value) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new NotSupportedException("Only enums are supported.");
}
}
Steven is correct, but you can narrow it a little before you throw an exception
public SomeType SomeFunction<T>(T value) where T : struct
精彩评论