开发者

Restricting generic function to only work on Enums [duplicate]

开发者 https://www.devze.com 2023-01-25 18:00 出处:网络
This question already has answers here: Anyone know a good workaround for the lack of an enum generic constraint?
This question already has answers here: Anyone know a good workaround for the lack of an enum generic constraint? (12 answers) Interesting "params of ref" feature, any workarounds? (5 answers) Closed 9 years ago.

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 Enums 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
0

精彩评论

暂无评论...
验证码 换一张
取 消