【问题标题】:can C# enums be declared as of bool type?可以将 C# 枚举声明为 bool 类型吗?
【发布时间】:2010-12-28 01:54:43
【问题描述】:

我可以将 c# enum 声明为 bool 之类的吗:

enum Result : bool
{
    pass = true,
    fail = false
}

【问题讨论】:

  • 仅当您添加第三个值 FileNotFound
  • 即使有可能,我也不认为这只是令人困惑。 if(!IsFailed) {...} 将完全无法阅读。
  • 说bool success = Result.Pass 而不是bool success = true 有什么好处?这是可读性的东西吗?
  • 任何没有深入了解编程最佳实践和认识论哲学的人都需要了解@blu 评论的智慧,如果您希望获得启发,请参阅每日 WTF 文章 What Is Truth?。

标签: c# enums boolean


【解决方案1】:

怎么样:

class Result
    {
        private Result()
        {
        }
        public static Result OK = new Result();
        public static Result Error = new Result();
        public static implicit operator bool(Result result)
        {
            return result == OK;
        }
        public static implicit operator Result( bool b)
        {
            return b ? OK : Error;
        }
    }

你可以像 Enum 或 bool 一样使用它,例如 var x = 结果.OK; 结果 y = true; 如果(x) ... 要么 if(y==Result.OK)

【讨论】:

    【解决方案2】:

    如果除了枚举常量的类型值之外,您还需要枚举包含布尔数据,您可以向枚举添加一个简单的属性,采用布尔值。然后你可以为你的枚举添加一个扩展方法来获取属性并返回它的布尔值。

    public class MyBoolAttribute: Attribute
    {
            public MyBoolAttribute(bool val)
            {
                Passed = val;
            }
    
            public bool Passed
            {
                get;
                set;
            }
    }
    
    public enum MyEnum
    {
            [MyBoolAttribute(true)]
            Passed,
            [MyBoolAttribute(false)]
            Failed,
            [MyBoolAttribute(true)]
            PassedUnderCertainCondition,
    
            ... and other enum values
    
    }
    
    /* the extension method */    
    public static bool DidPass(this Enum en)
    {
           MyBoolAttribute attrib = GetAttribute<MyBoolAttribute>(en);
           return attrib.Passed;
    }
    
    /* general helper method to get attributes of enums */
    public static T GetAttribute<T>(Enum en) where T : Attribute
    {
           Type type = en.GetType();
           MemberInfo[] memInfo = type.GetMember(en.ToString());
           if (memInfo != null && memInfo.Length > 0)
           {
                 object[] attrs = memInfo[0].GetCustomAttributes(typeof(T),
                 false);
    
                 if (attrs != null && attrs.Length > 0)
                    return ((T)attrs[0]);
    
           }
           return null;
    }
    

    【讨论】:

      【解决方案3】:

      它说

      允许的枚举类型为 byte、sbyte、short、ushort、int、uint、long 或 ulong。

      enum (C# Reference)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 2015-04-26
        • 2022-01-23
        • 1970-01-01
        • 2013-01-13
        相关资源
        最近更新 更多