Convert array of enum values to bit-flag combination

二次信任 提交于 2019-12-22 04:15:09

问题


How to create a bit-flag combination from an array of enum values in the simplest most optimal way in C# 2.0. I have actually figured out a solution but I am just not satisfied with the complexity here.

enum MyEnum
{
    Apple = 0,
    Apricot = 1,
    Breadfruit = 2,
    Banana = 4
}

private int ConvertToBitFlags(MyEnum[] flags)
{
    string strFlags = string.Empty;
    foreach (MyEnum f in flags)
    {
        strFlags += strFlags == string.Empty ?
            Enum.GetName(typeof(MyEnum), f) :
            "," + Enum.GetName(typeof(MyEnum), f);
    }
    return (int)Enum.Parse(typeof(MyEnum), strFlags);
}

回答1:


int result = 0;
foreach (MyEnum f in flags)
{
    result |= f; // You might need to cast — (int)f.
}
return result;

OTOH, you should use the FlagsAttribute for improved type safety:

[Flags]
enum MyEnum { ... }

private MyEnum ConvertToBitFlags(MyEnum[] flags)
{
    MyEnum result = 0;
    foreach (MyEnum f in flags)
    {
        result |= f;
    }
    return result;
}

Better still, by using FlagsAttribute you may be able to avoid using a MyEnum[] entirely, thus making this method redundant.




回答2:


Here's a shorter generic extension version:

public static T ConvertToFlag<T>(this IEnumerable<T> flags) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
        throw new NotSupportedException($"{typeof(T).ToString()} must be an enumerated type");

    return (T)(object)flags.Cast<int>().Aggregate(0, (c, n) => c |= n);
}

And using:

[Flags]
public enum TestEnum
{
    None = 0,
    Test1 = 1,
    Test2 = 2,
    Test4 = 4
}

[Test]
public void ConvertToFlagTest()
{
    var testEnumArray = new List<TestEnum> { TestEnum.Test2, TestEnum.Test4 };

    var res = testEnumArray.ConvertToFlag();

    Assert.AreEqual(TestEnum.Test2 | TestEnum.Test4, res);
}


来源:https://stackoverflow.com/questions/7616775/convert-array-of-enum-values-to-bit-flag-combination

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!