Mar*_*lon 5 c# generics enum-flags
我想创建一个扩展方法来检查枚举是否有一个标志.
DaysOfWeek workDays = DaysOfWeek.Monday | DaysOfWeek.Tuesday | DaysOfWeek.Wednesday;
// instead of this:
if ((workDays & DaysOfWeek.Monday) == DaysOfWeek.Monday)
...
// I want this:
if (workDays.ContainsFlag(DaysOfWeek.Monday))
...
Run Code Online (Sandbox Code Playgroud)
我怎么能做到这一点?(如果有一个类已经完成了这个,那么我会很感激如何解释这个问题;我已经把这个方法弄得太久了!)
提前致谢
Pau*_*ane 11
.NET 4已经包含了这个功能,如果可能的话,升级.
days.HasFlag(DaysOfWeek.Monday);
Run Code Online (Sandbox Code Playgroud)
如果无法升级,这里是所述方法的实现:
public bool 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());
return ((uThis & uFlag) == uFlag);
}
Run Code Online (Sandbox Code Playgroud)
您可以轻松构建等效的扩展方法:
public static bool HasFlag(this Enum @this, Enum flag)
{
// as above, but with '@this' substituted for 'this'
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1300 次 |
最近记录: |