【问题标题】:Check if more than one flag set in generic extension检查通用扩展中是否设置了多个标志
【发布时间】:2012-11-16 04:12:41
【问题描述】:

借用这个问题How do I check if more than one enum flag is set?的代码我已经尝试实现一个通用扩展来执行这个测试。

我的第一次尝试如下。

public static bool ExactlyOneFlagSet(this Enum enumValue)
{
    return !((enumValue & (enumValue - 1)) != 0);
}

导致

运算符“-”不能应用于“System.Enum”类型的操作数和 'int'

好吧,有道理,所以我想我会尝试这样的事情

public static bool ExactlyOneFlagSet<T>(this T enumValue) where T : struct, IConvertible
{
    return !(((int)enumValue & ((int)enumValue - 1)) != 0);
}

导致

无法将类型“T”转换为“int”

在阅读了这种行为之后,这也是有道理的,但是究竟如何实现这种扩展方法。有好心人帮忙吗???

【问题讨论】:

    标签: c# enums extension-methods flags


    【解决方案1】:

    由于你约束T 来实现IConvertible,你可以简单地调用ToInt32

    public static bool ExactlyOneFlagSet<T>(this T enumValue)
        where T : struct, IConvertible
    {
        int v = enumValue.ToInt32(null);
        return (v & (v - 1)) == 0;
    }
    

    【讨论】:

    • 看来您需要提供一种文化! int v = enumValue.ToInt32(System.Threading.Thread.CurrentThread.CurrentCulture);我错了吗?否则看起来很漂亮,现在测试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2015-12-29
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    相关资源
    最近更新 更多