2009-12-18 11 views
14

Kann ich erklären, C# enum als bool wie:können C# enums als Bool-Typ deklariert werden?

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

nur, wenn Sie einen dritten Wert hinzufügen, FileNotFound – blu

+0

Selbst wenn es möglich wäre, ich sehe das nicht als etwas zu sein, aber verwirrend . 'if (! IsFailed) {...} wäre komplett unlesbar. –

+1

Was ist der Vorteil von 'bool success = Result.Pass' anstelle von' bool success = true'? Ist das eine Lesbarkeit? –

Antwort

17

, wenn Sie Ihre Enum benötigen boolean Daten zusätzlich zu dem Wert Typs ENUM konstant enthalten, könnten Sie ein einfaches Attribut zu Ihrem Enum hinzufügen, einen Booleschen Wert annehmen. Dann können Sie eine Erweiterungsmethode für Ihre Enumeration hinzufügen, die das Attribut abruft und dessen booleschen Wert zurückgibt.

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

Es sagt

Die zugelassenen Typen für eine Enumeration sind Byte, sbyte, kurz, ushort, int, uint, long oder ulong .

enum (C# Reference)

6

Was:

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

Sie es wie Enum oder wie bool verwenden können, zum Beispiel var x = Result.OK; Ergebnis y = wahr; if (x) ... oder if (y == Result.OK)

Verwandte Themen