【问题标题】:Enum is defined does not work as expected [duplicate]枚举的定义不能按预期工作[重复]
【发布时间】:2017-09-12 07:07:26
【问题描述】:

我有以下枚举需要根据客户选择进行验证

    [Flags]
    enum Colour
    {
        Black = 1,
        Blue = 2,
        Green = 4,
        Yellow = 8
    }



var isValid = Enum.IsDefined(typeof(Colour), 5);

如果 5 是有效值,为什么返回 false (Colour.Black | Colour.Green)

【问题讨论】:

  • 您是否希望调用生成所有可能的组合?它只检查那些实际定义的。
  • 5 不是枚举中定义的值。仅当您有一个值为 5 的条目时才为真。
  • 好的。那怎么检查呢?
  • 5 = 4 + 1,检查是否定义了4并检查是否定义了1。
  • @codejunkie - 那么您面临的实际问题是什么?关于十几个枚举

标签: c# .net enums


【解决方案1】:

因为这是正确的结果。 "如果 enumType 是使用 FlagsAttribute 属性定义的枚举,如果 value 中设置了多个位字段但 value 不对应于复合枚举值,或者 value 是多个名称的字符串连接,则该方法返回 false位标志。” 有关 IsDefined 工作原理的详细信息,请参阅MSDN

UPD:任何枚举的解决方案:

static class EnumExtensions
{
    public static bool IsSuitable(Type enumType, int value)
    {
        if (!enumType.IsEnum)
        {
            throw new ArgumentException(nameof(enumType));
        }

        var entities = Enum.GetValues(enumType);
        int composite = 0;
        foreach (var entity in entities)
        {
            composite |= (int)entity;
        }

        return (composite | value) == composite;
    }
}

它给出了这个结果:

var suit = EnumExtensions.IsSuitable(typeof(Colour), 5); // true
var suit2 = EnumExtensions.IsSuitable(typeof(Colour), 333); //false

【讨论】:

  • private readonly int composite = Colour.Black | Colour.Blue | Colour.Green | Colour.Yellow; 这不会编译
  • 如果Colour 的内容更改为(“保存输入”并)使其“面向未来”:private readonly Colour composite = Enum.GetValues(typeof(Colour)).OfType<Colour>().Aggregate((Colour)0, (c, v) => c | v);
  • 谢谢,但现在 IsColour(int value) 无法编译
  • 一会儿。一个通用的解决方案正在接近中。
【解决方案2】:

Enum.IsDefined() 函数的返回值取决于枚举定义。 您实际上会检查“5”是否在您定义的枚举的值集中。

【讨论】:

    【解决方案3】:
        [Flags]
        enum Colour
        {
            Black = 1,  // 0001
            Blue = 2,   // 0010
            Green = 4,  // 0100
            Yellow = 8  // 1000
        }
    
        static void Main(string[] args)
        {
            var isValid = Enum.IsDefined(typeof(Colour), 5); // 5 is 0101
        }
    

    枚举.IsDefined: 返回指定枚举中是否存在具有指定值的常量的指示。

    在您的示例中,您有值 1,2,4,8 为什么您认为值 5 应该返回 true ??

        [Flags]
        enum Colour
        {
            Black = 1,
            Blue = 785,
            Green = 4,
            Yellow = 666
        }
    
        static void Main(string[] args)
        {
            var isValid = Enum.IsDefined(typeof(Colour), 666); // true
            var isValid2 = Enum.IsDefined(typeof(Colour), 785); // true
            var isValid3 = Enum.IsDefined(typeof(Colour), 5); // false
        }
    

    【讨论】:

    • 这和我贴的代码有什么区别?
    • 在您的枚举中,您没有在二进制表示中表示 5 的值(添加 Red = 5),您的验证将是真的
    • 你在你的例子中寻找repreintation 0101
    • 抱歉还是没找到你
    • 当你问 5 时你认为这个函数是做什么的?
    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多