可以将C#枚举声明为bool类型吗?

时间:2009-12-18 15:16:24

标签: c# enums boolean

我可以将c#enum声明为bool,如:

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

3 个答案:

答案 0 :(得分:22)

它说

枚举的已批准类型为 byte,sbyte,short,ushort,int,uint,long或ulong

enum (C# Reference)

答案 1 :(得分:19)

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

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

答案 2 :(得分: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;
        }
    }

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