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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1928799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:56:23  来源:igfitidea点击:

can C# enums be declared as of bool type?

c#enumsboolean

提问by satya

Can I declare c# enumas boollike:

我可以将 c# 声明enumbool

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

采纳答案by Terje

if you need your enum to contain boolean data in addition to the enum constant's type value, you could add a simple attribute to your enum, taking a boolean value. Then you can add an extension method for your enum that fetches the attribute and returns its boolean value.

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

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

回答by Adriaan Stander

It says

它说

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

批准的枚举类型是byte、sbyte、short、ushort、int、uint、long 或 ulong

enum (C# Reference)

枚举(C# 参考)

回答by zbychuk

What about:

关于什么:

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

You can use it like Enum or like bool, for example var x = Result.OK; Result y = true; if(x) ... or if(y==Result.OK)

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