Anyone know a good workaround for the lack of an enum generic constraint?

后端 未结 12 1388
情书的邮戳
情书的邮戳 2020-11-22 15:37

What I want to do is something like this: I have enums with combined flagged values.

public static class EnumExtension
{
    public static bool IsSet

        
12条回答
  •  孤城傲影
    2020-11-22 15:45

    As of C# 7.3, you can use the Enum constraint on generic types:

    public static TEnum Parse(string value) where TEnum : Enum
    {
        return (TEnum) Enum.Parse(typeof(TEnum), value);
    }
    

    If you want to use a Nullable enum, you must leave the orginial struct constraint:

    public static TEnum? TryParse(string value) where TEnum : struct, Enum
    {
        if( Enum.TryParse(value, out TEnum res) )
            return res;
        else
            return null;
    }
    

提交回复
热议问题