栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在C#中使用位掩码

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在C#中使用位掩码

传统方法是在上使用

Flags
属性
enum

[Flags]public enum Names{    None = 0,    Susan = 1,    Bob = 2,    Karen = 4}

然后,您将按照以下方式检查特定名称:

Names names = Names.Susan | Names.Bob;// evaluates to truebool susanIsIncluded = (names & Names.Susan) != Names.None;// evaluates to falsebool karenIsIncluded = (names & Names.Karen) != Names.None;

逻辑按位组合可能很难记住,因此我可以通过一

FlagsHelper
堂课* 使自己的生活更轻松:

// The casts to object in the below pre are an unfortunate necessity due to// C#'s restriction against a where T : Enum constraint. (There are ways around// this, but they're outside the scope of this simple illustration.)public static class FlagsHelper{    public static bool IsSet<T>(T flags, T flag) where T : struct    {        int flagsValue = (int)(object)flags;        int flagValue = (int)(object)flag;        return (flagsValue & flagValue) != 0;    }    public static void Set<T>(ref T flags, T flag) where T : struct    {        int flagsValue = (int)(object)flags;        int flagValue = (int)(object)flag;        flags = (T)(object)(flagsValue | flagValue);    }    public static void Unset<T>(ref T flags, T flag) where T : struct    {        int flagsValue = (int)(object)flags;        int flagValue = (int)(object)flag;        flags = (T)(object)(flagsValue & (~flagValue));    }}

这将允许我将以上代码重写为:

Names names = Names.Susan | Names.Bob;bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);

注意,我还可以

Karen
通过执行以下操作添加到集合中:

FlagsHelper.Set(ref names, Names.Karen);

我可以

Susan
用类似的方式删除:

FlagsHelper.Unset(ref names, Names.Susan);

*正如Porges所指出的,

IsSet
.NET 4.0中已经存在上述方法的等效项:
Enum.HasFlag
。不过,
Set
Unset
方法似乎没有等效项。所以我仍然会说这堂课有一些优点。


注意:使用枚举只是解决此问题的 常规 方法。您可以完全翻译上面的所有代码以改为使用int,它也将正常工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402894.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号