将枚举值数组转换为标志枚举

时间:2014-06-13 11:06:12

标签: c# arrays enums

我正在尝试以这里指定的方式实现功能:

Specific solution

但是,我尝试将其作为通用方法用作扩展程序:

    public static TEnum? Merge<TEnum>(this IEnumerable<TEnum> values)
        where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        Nullable<TEnum> merged = null;
        if (values == null || values.Count() == 0)
            return null;

        foreach(TEnum value in values)
        {
            if (merged == null)
                merged = value;
            else
            {
                merged = merged | value;
            }
        }
        return merged;
    }

然而问题是这一行:

merged = merged | value;

不会编译。我得到的消息是:

运营商&#39; |&#39;不能应用于&#39; TEnum类型的操作数?&#39;和&#39; TEnum&#39;

是否可以编写这个将枚举值数组转换为标志枚举的通用方法?

3 个答案:

答案 0 :(得分:3)

这里有几个问题,但最大的问题是泛型不支持运算符 - 而|是运算符。你可以通过object破解它,但是你有拳击。这就是我要做的事情 - 它会生成一些动态的IL per-enum类型(仅限一次),并使用它来直接进行&#34;或&#34;没有拳击。请注意,它还使用0作为默认返回(远远超出预期,IMO),并避免显式Count(),因为这可能是不可预测的昂贵,并且可能会破坏枚举器(您可以&#39; t保证您可以多次枚举数据):

using System;
using System.Collections.Generic;
using System.Reflection.Emit;

public static class EnumUtils
{
    public static TEnum Merge<TEnum>(this IEnumerable<TEnum> values)
        where TEnum : struct
    {
        TEnum merged = default(TEnum);
        if (values != null)
        {
            var or = Operator<TEnum>.Or;
            foreach (var value in values)
            {
                merged = or(merged, value);
            }
        }
        return (TEnum)(object)merged;
    }
    static class Operator<T>
    {
        public static readonly Func<T, T, T> Or;

        static Operator()
        {
            var dn = new DynamicMethod("or", typeof(T),
                new[] { typeof(T), typeof(T) }, typeof(EnumUtils));
            var il = dn.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Or);
            il.Emit(OpCodes.Ret);
            Or = (Func<T, T, T>)dn.CreateDelegate(typeof(Func<T, T, T>));
        }

    }
}
static class Program {

    [Flags]
    public enum Foo
    {
        None = 0, A = 1,  B =2, C = 4
    }
    static unsafe void Main()
    {
        var merged = EnumUtils.Merge(new[] { Foo.A, Foo.C });

    }
}

编辑:如果你真的必须为&#34; null或空&#34;返回null case,那么你可以使用以下调整 - 但我强调:IMO这是一个不正确的实现 - 简单地返回0(又名default(TEnum))更为正确这种情况。

public static TEnum? Merge<TEnum>(this IEnumerable<TEnum> values)
    where TEnum : struct
{
    if (values == null) return null;
    using (var iter = values.GetEnumerator())
    {
        if (!iter.MoveNext()) return null;
        TEnum merged = iter.Current;
        var or = Operator<TEnum>.Or;
        while(iter.MoveNext())
        {
            merged = or(merged, iter.Current);
        }
        return merged;
    }
}

这是做什么的:

  • 检查空序列,短路
  • 获取序列迭代器,并尝试读取一个值 - 如果没有
  • 则短路
  • 使用当前(第一个)值作为种子,并获取运算符
  • 迭代序列,连续应用运算符
  • 返回合并值

答案 1 :(得分:1)

Linq 中的 1 行,不需要辅助方法:

var result = enumArray.Aggregate ((TestEnum)0, (a, b) => a | b);

但如果你不想记住这段代码,也可以使用扩展方法:

private static T Merge<T> (this T[] i_enumValues)
// - or -
// private static T Merge<T> (params T[] i_enumValues)
  where T : Enum
{
  var type = typeof (T);
  if (!type.IsDefined (typeof (FlagsAttribute), false))
    throw new ArgumentException ($"The given enum type '{type}' does not have the {nameof (FlagsAttribute)}.");

  var zero = (T)Convert.ChangeType (0, Enum.GetUnderlyingType (type));

  var result = i_enumValues.Aggregate (zero, (a, b) => (dynamic)a | (dynamic)b);

  return result;
}

概念证明:

[Flags]
public enum TestEnum : ulong
{
  First  = 1   << 0,
  Second = 1   << 1,
  Third  = 1   << 2,
  Fourth = 1   << 3,
  Fifth  = 1   << 4,
  Bit40  = 1ul << 40
}

private static void Main (string[] args)
{
  var enumArray = new[] { TestEnum.First, TestEnum.Second, TestEnum.Third, TestEnum.Bit40 };
  var result    = enumArray.Aggregate ((TestEnum)0, (a, b) => a | b);
  var result2   = Merge (enumArray);
}

输出:

result  = First | Second | Third | Bit40
result2 = First | Second | Third | Bit40
result .ToString ("X") -> "0000010000000007"
result2.ToString ("X") -> "0000010000000007"

答案 2 :(得分:0)

我需要这种能力,很高兴找到Marc的答案。我尝试使用一些较新的语言功能。这就是我想出的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

public static class Extensions
{
    /// <summary>
    /// Intended for merging an enumeration of flags enum into a single value.
    /// </summary>
    public static TEnum Merge<TEnum>(this IEnumerable<TEnum> values)
        where TEnum : struct, IConvertible
    {
        var type = typeof(TEnum);
        if (!type.IsEnum)
            throw new InvalidOperationException($"{type} is not an enum type.");

        return values.DefaultIfEmpty(default(TEnum)).Aggregate(Operator<TEnum>.Or);
    }

    static class Operator<T>
    {
        private static readonly Lazy<Func<T, T, T>> LazyOr;
        private static readonly Lazy<Func<T, T, T>> LazyAnd;

        public static Func<T, T, T> Or => LazyOr.Value;
        public static Func<T, T, T> And => LazyAnd.Value;

        static Operator()
        {
            var enumType = typeof(T);
            var underType = enumType.GetEnumUnderlyingType();
            var leftParam = Expression.Parameter(enumType, "left");
            var rightParam = Expression.Parameter(enumType, "right");
            var leftCast = Expression.ConvertChecked(leftParam, underType);
            var rightCast = Expression.ConvertChecked(rightParam, underType);

            Lazy<Func<T, T, T>> CreateLazyOp(Func<Expression, Expression, BinaryExpression> opFunc) =>
            new Lazy<Func<T, T, T>>(() =>
            {
                var op = opFunc(leftCast, rightCast);
                var resultCast = Expression.ConvertChecked(op, enumType);
                var l = Expression.Lambda<Func<T, T, T>>(resultCast, leftParam, rightParam);
                return l.Compile();
            });

            LazyOr = CreateLazyOp(Expression.Or);
            LazyAnd = CreateLazyOp(Expression.And);

        }
    }
}