2009-12-18 57 views
14

我可以声明C#enumbool像:C#枚举可以声明为bool类型吗?

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

仅当您添加第三个值,FileNotFound – blu

+0

即使有可能,我不认为这为任何东西,但令人困惑。 '如果(!IsFailed){...}'完全不可读。 –

+1

说'bool success = Result.Pass'而不是'bool success = true'有什么好处?这是一个可读性的东西吗? –

回答

17

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

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

它说

经批准的类型枚举是字节,为sbyte,短,USHORT,INT,UINT,长,或乌龙

enum (C# Reference)

6

什么:

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

您可以使用它像枚举或类似BOOL,例如 变种X = Result.OK; 结果y = true; 如果(X)... 或 如果(Y == Result.OK)