我有一种使用枚举将位掩码转换为天列表的方法。我正在尝试相反的操作,但是遇到了麻烦。我有DaysOfWeekToEnum工作,但没有DaysOfWeekFromEnum。以下是我正在尝试做的事情。有人可以帮忙吗?

public static short DaysOfWeekFromEnum(IEnumerable<DaysInWeekIds> daysOfWeek)
{
    short mask;

    foreach (var item in daysOfWeek)
    {
        mask &= item; // ????
    }

    return mask
}

public static IEnumerable<DaysInWeekIds> DaysOfWeekToEnum(short mask)
{
    var values = new List<DaysInWeekIds>();

    foreach (short enumValue in Enum.GetValues(typeof(DaysInWeekIds)))
    {
        if (mask & enumValue == enumValue)
        {
            values.Add((DaysInWeekIds) Enum.ToObject(typeof(DaysInWeekIds),
                enumValue));
        }
    }

    return values;
}

/// <summary> The days in week ids. </summary>
public enum DaysInWeekIds : short
{
    M = 1,
    Tu = 2,
    W = 4,
    Th = 8,
    F = 16,
    Sa = 32,
    Su = 64
}

最佳答案

设置附加位应该是|=,而不是&=

您也可以将字符串表示形式连接在一起,并将结果传递给Enum.Parse方法。这样效率不高,但是代码看起来会更短。

var res = (DaysInWeekIds)Enum.Parse(
    typeof(DaysInWeekIds)
,   string.Join(",", daysOfWeek.Select(d => d.ToString()).ToArray())
);


这将为25link to ideone)返回{M, Th, F}

10-08 06:58