перечисления C# могут быть объявлены с типа bool?

Я могу объявить c# enum как bool как:

enum Result : bool
{
    pass = true,
    fail = false
}
16
задан Filip Ekberg 30 April 2010 в 14:01
поделиться

3 ответа

если вам нужно, чтобы ваше перечисление содержало логические данные в дополнение к значению типа константы перечисления, вы можете добавить в свое перечисление простой атрибут, принимающий логическое значение. Затем вы можете добавить метод расширения для своего перечисления, который выбирает атрибут и возвращает его логическое значение.

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
ответ дан 30 November 2019 в 15:44
поделиться

В нем говорится

Утвержденные типы для перечисления: byte, sbyte, short, ushort, int, uint, long или ulong .

enum ( Справочник по C #)

22
ответ дан 30 November 2019 в 15:44
поделиться

А как насчет:

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; Result y = true; if (x) ... { {1}} или if (y == Result.OK)

7
ответ дан 30 November 2019 в 15:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: