C#枚举可以声明为布尔类型吗?

19

我能否像这样将c#中的 enum 声明为 bool

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

21
只有在添加第三个值"FileNotFound"时才会发生。 - blu
即使可能,我认为这只会让人感到困惑。if(!IsFailed) {...}将完全无法阅读。 - Jim H.
1
bool success = Result.Pass而不是bool success = true有什么好处?这是可读性的问题吗? - Joseph Yaduvanshi
1
如果您没有深入了解编程最佳实践和认识论哲学的知识,无法理解@blu评论中的智慧,请查看《每日WTF》文章真相是什么?以获得启迪。 - Mark Amery
3个回答

25

它说:

枚举类型的可接受类型包括 byte、sbyte、short、ushort、int、uint、long 或 ulong

枚举 (C# 参考)


21
如果你需要在枚举常量的类型值之外包含布尔数据,可以为枚举添加一个简单的属性,接受布尔值。然后,你可以为枚举添加一个扩展方法,获取该属性并返回其布尔值。
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;
}

7

关于什么:

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;
        }
    }

你可以像使用枚举类型或布尔类型那样使用它,例如: var x = Result.OK; Result y = true; if(x) ... 或者 if(y==Result.OK)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接