简体   繁体   English

检查通用扩展中是否设置了多个标志

[英]Check if more than one flag set in generic extension

Borrowing the code from this question How do I check if more than one enum flag is set? 借用此问题的代码如何检查是否设置了多个枚举标志? I have tried to implement a generic extension that performs this test. 我试图实现执行此测试的通用扩展。

My first attempt was the following. 我的第一次尝试如下。

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

Which resulted in 结果导致了

Operator '-' cannot be applied to operands of type 'System.Enum' and 'int' 运算符' - '不能应用于'System.Enum'和'int'类型的操作数

OK make sense, so I thought I'd try something like this 好有意义,所以我想我会尝试这样的事情

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

Which resulted in 结果导致了

Cannot convert type 'T' to 'int' 无法将类型'T'转换为'int'

Which also makes sense after reading about this behaviour but then how on earth can this extension method be implemented. 在阅读了这种行为之后这也是有意义的,但接下来如何实现这种扩展方法。 Anyone kind enough to help??? 有人帮忙吗?

Since you contrain T to implement IConvertible , you can simply call ToInt32 : 由于您禁止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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM