如何编写从给定枚举列表计算位掩码的扩展

发布于 2025-01-17 04:17:25 字数 298 浏览 2 评论 0原文

我有一个枚举

public enum MyEnum{
   None =0,
   First = 1,
   Second = 2,
   Thirds = 4
}

我有这些枚举的列表

List<MyEnum> MyEnumList;

我想获得 MyEnum 选择的位掩码结果

int bitMask = Enum.GetBitMask<MyEnum>(MyEnumList);

I have an enum

public enum MyEnum{
   None =0,
   First = 1,
   Second = 2,
   Thirds = 4
}

I have a list of these enums

List<MyEnum> MyEnumList;

I would like to get a bitmask result of MyEnum selection as

int bitMask = Enum.GetBitMask<MyEnum>(MyEnumList);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风情万种。 2025-01-24 04:17:25

这是我的解决方案,我还找不到更优雅的解决方案。

public static class EnumExtensions
{
    public static int GetBitmask<T>(List<T> collection)
    {
        if (!collection?.Any() ?? true)
            return 0;
        int output = Convert.ToInt32(collection.First());
        collection.ForEach(x => output |= Convert.ToInt32(x));
        return output;
    }
} 

这是你如何称呼它

int bitMask = EnumExtensions.GetBitmask(MyEnumList);

Here is my solution, I could not find anything more elegant yet.

public static class EnumExtensions
{
    public static int GetBitmask<T>(List<T> collection)
    {
        if (!collection?.Any() ?? true)
            return 0;
        int output = Convert.ToInt32(collection.First());
        collection.ForEach(x => output |= Convert.ToInt32(x));
        return output;
    }
} 

Here is how you would call it

int bitMask = EnumExtensions.GetBitmask(MyEnumList);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文