如何比较C#中的标志? [英] How to Compare Flags in C#?
本文介绍了如何比较C#中的标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[Flags]
public enum FlagTest
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4
}
我无法使if语句求值为true。
FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;
if(testItem == FlagTest.Flag1)
{
//做某事,
//但是这不是真的。
}
我如何使这个成真?
解决方案
在.NET 4中有一个新方法 Enum.HasFlag 。这可以写成:
if(testItem.HasFlag(FlagTest.Flag1))
{
// Do Stuff
}
这是更可读的,IMO。
.NET源代码表示与所接受的答案相同的逻辑:
public Boolean HasFlag(Enum flag){
if(!this.GetType()。IsEquivalentTo(flag.GetType())){
throw new ArgumentException(
Environment.GetResourceString(
Argument_EnumTypeDoesNotMatch,
flag.GetType(),
this.GetType()));
}
ulong uFlag = ToUInt64(flag.GetValue());
ulong uThis = ToUInt64(GetValue());
// test predicate
return((uThis& uFlag)== uFlag);
}
I have a flag enum below.
[Flags]
public enum FlagTest
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4
}
I cannot make the if statement evaluate to true.
FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;
if (testItem == FlagTest.Flag1)
{
// Do something,
// however This is never true.
}
How can I make this true?
解决方案
In .NET 4 there is a new method Enum.HasFlag. This allows you to write:
if ( testItem.HasFlag( FlagTest.Flag1 ) )
{
// Do Stuff
}
which is much more readable, IMO.
The .NET source indicates that this performs the same logic as the accepted answer:
public Boolean HasFlag(Enum flag) {
if (!this.GetType().IsEquivalentTo(flag.GetType())) {
throw new ArgumentException(
Environment.GetResourceString(
"Argument_EnumTypeDoesNotMatch",
flag.GetType(),
this.GetType()));
}
ulong uFlag = ToUInt64(flag.GetValue());
ulong uThis = ToUInt64(GetValue());
// test predicate
return ((uThis & uFlag) == uFlag);
}
这篇关于如何比较C#中的标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文