我能否像这样将c#中的 enum
声明为 bool
:
enum Result : bool
{
pass = true,
fail = false
}
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;
}
关于什么:
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;
}
}
if(!IsFailed) {...}
将完全无法阅读。 - Jim H.bool success = Result.Pass
而不是bool success = true
有什么好处?这是可读性的问题吗? - Joseph Yaduvanshi