使用标志方法扩展枚举



我已经找到了关于如何创建扩展方法以从逐位枚举中读取单个值的好例子。但是现在C#4已经添加了HasFlag方法,它们真的不需要了

不过,我认为真正有用的是扩展设置单个标志
在许多情况下,我需要单独设置标志值
我想要一个具有此签名的扩展方法:

enumVariable.SetFlag(EnumType.SingleFlag, true);

或者可能:

enumVariable.SetFlag<EnumType>(EnumType.SingleFlag, true);

今天我在http://hugoware.net/blog/enums-flags-and-csharp.谢谢Hugo!运行良好的优秀代码。我稍微调整了一下,并将其添加到我现有的EnumExtender:中

public static class EnumExtender
{
    /// <summary>
    /// Adds a flag value to enum.
    /// Please note that enums are value types so you need to handle the RETURNED value from this method.
    /// Example: myEnumVariable = myEnumVariable.AddFlag(CustomEnumType.Value1);
    /// </summary>
    public static T AddFlag<T>(this Enum type, T enumFlag)
    {
        try
        {
            return (T)(object)((int)(object)type|(int)(object)enumFlag);
        }
        catch(Exception ex)
        {
            throw new ArgumentException(string.Format("Could not append flag value {0} to enum {1}",enumFlag, typeof(T).Name), ex);
        }
    }
    /// <summary>
    /// Removes the flag value from enum.
    /// Please note that enums are value types so you need to handle the RETURNED value from this method.
    /// Example: myEnumVariable = myEnumVariable.RemoveFlag(CustomEnumType.Value1);
    /// </summary>
    public static T RemoveFlag<T>(this Enum type, T enumFlag)
    {
        try
        {
            return (T)(object)((int)(object)type & ~(int)(object)enumFlag);
        }
        catch (Exception ex)
        {
            throw new ArgumentException(string.Format("Could not remove flag value {0} from enum {1}", enumFlag, typeof(T).Name), ex);
        }
    }
    /// <summary>
    /// Sets flag state on enum.
    /// Please note that enums are value types so you need to handle the RETURNED value from this method.
    /// Example: myEnumVariable = myEnumVariable.SetFlag(CustomEnumType.Value1, true);
    /// </summary>
    public static T SetFlag<T>(this Enum type, T enumFlag, bool value)
    {
        return value ? type.AddFlag(enumFlag) : type.RemoveFlag(enumFlag);
    }
    /// <summary>
    /// Checks if the flag value is identical to the provided enum.
    /// </summary>
    public static bool IsIdenticalFlag<T>(this Enum type, T enumFlag)
    {
        try
        {
            return (int)(object)type == (int)(object)enumFlag;
        }
        catch
        {
            return false;
        }
    }
    /// <summary>
    /// Convert provided enum type to list of values.
    /// This is convenient when you need to iterate enum values.
    /// </summary>
    public static List<T> ToList<T>()
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException();
        var values = Enum.GetNames(typeof(T));
        return values.Select(value => value.ToEnum<T>()).ToList();
    }
    /// <summary>
    /// Present the enum values as a comma separated string.
    /// </summary>
    public static string GetValues<T>()
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException();
        var values = Enum.GetNames(typeof(T));
        return string.Join(", ", values);
    }
}

我做了一些对我有用而且非常简单的事情。由于动态铸造的使用,可能效率不高。但也许你会喜欢它?

public static T SetFlag<T>(this Enum value, T flag, bool set)
{
    Type underlyingType = Enum.GetUnderlyingType(value.GetType());
    // note: AsInt mean: math integer vs enum (not the c# int type)
    dynamic valueAsInt = Convert.ChangeType(value, underlyingType);
    dynamic flagAsInt = Convert.ChangeType(flag, underlyingType);
    if (set)
    {
        valueAsInt |= flagAsInt;
    }
    else
    {
        valueAsInt &= ~flagAsInt;
    }
    return (T)valueAsInt;
}

我不确定你的问题是什么,但如果你问这是否可能,我不得不说不是,不是用这个确切的语法。

枚举是值类型,因此是按值传递的。因此,一个接收枚举值的方法,如SetFlag,将接收到它的COPY。即使它设置了一个标志,这种更改也将局限于方法范围,而不是它调用的枚举。

您可以将它传递给一个带有ref修饰符的方法,比如:SetFlag(ref enumVariable, EnumType.SingleFlag),但据我所知,它不支持作为扩展方法。

您可以创建一个通用枚举助手类:

public static class EnumHelper
{
    public void SetFlag<TEnum>(ref TEnum enumValue, TEnum flag)
    {
         enumValue = enumValue | flag;
    }
}

或者,创建一个返回新值的SetFlag方法,而不是修改现有变量。

public static TEnum SetFlag<TEnum>(this TEnum enumValue, TEnum flag)
{
    return enumValue | flag;
}

也许没有你希望的那么漂亮,但你可以做得很简单:)

enumVariable |= EnumType.SingleFlag;

您可能需要为每个枚举实现方法,因为您不能以这种方式约束枚举:

public static T SetFlag<T>(this T @this, T flag, Boolean state) where T : enum { ... }

无论如何,C#中不允许在泛型类型上重载运算符,因此不能在不进行强制转换的情况下使用泛型类型t。

解决方案

所以你的扩展方法必须是这样的:

public static MyFlag SetFlag(this MyFlag @this, MyFlag flag, Boolean state) 
{
    return state ? (@this | flag) : (@this & ~flag);
}

最新更新