14
A
回答
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
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)
相关问题
- 1. 可能声明枚举类型的函数吗?
- 2. 类C++中的枚举声明,在类中枚举的问题
- 3. C++枚举类可以有方法吗?
- 4. C#语言枚举声明
- 5. 枚举声明中枚举数的类型
- 6. 声明枚举
- 7. 如何声明一个类属性作为枚举类型
- 8. 我们可以在java中使用C++类型枚举吗?
- 9. 可以在枚举声明中修改实例变量吗?
- 10. 枚举声明点
- 11. 我可以从泛型类型转换为C#中的枚举吗?
- 12. c#到C++/cli枚举声明
- 13. C#枚举类型安全吗?
- 14. 此枚举声明符合标准吗?
- 15. 枚举问题:重新声明为不同类型的符号
- 16. 为枚举类型
- 17. Perl有枚举类型吗?
- 18. 如何在C#声明枚举
- 19. 前向声明枚举Objective-C
- 20. 如何声明“静态”类/枚举?
- 21. 强制子类声明枚举
- 22. 在派生类中声明枚举
- 23. 获取声明枚举的类
- 24. 类似于使用枚举的声明?
- 25. 可以枚举类型的接口
- 26. 是否有可能为我的奇怪枚举类型声明FromJSON实例?
- 27. 是否有可能为特定类型的枚举声明swift通用?
- 28. 什么类型可以声明为const?
- 29. 你可以声明一个可变长度的泛型类型声明吗?
- 30. SystemVerilog枚举可以为null吗?
仅当您添加第三个值,FileNotFound – blu
即使有可能,我不认为这为任何东西,但令人困惑。 '如果(!IsFailed){...}'完全不可读。 –
说'bool success = Result.Pass'而不是'bool success = true'有什么好处?这是一个可读性的东西吗? –