2012-11-16 30 views
0

借用此问题的代码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' 和 '廉政'

OK有意义的操作数,所以我想我会尝试这样的事情

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

这就造成了

不能键入“T”转换为“廉政”

阅读有关此行为,但随后如何在地球上可以在此扩展方法实施之后也是情理之中。任何人都可以帮助吗?

回答

2

既然你contrain 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; 
} 
+0

看起来你,你需要提供一个文化! int v = enumValue.ToInt32(System.Threading.Thread.CurrentThread.CurrentCulture);我错了吗?否则看起来很美,现在测试 –

相关问题