C#扩展枚举的别名
用途:
- 提高代码的可读性.
- 打印到日志系统,方便于调试.
代码:
- 首先编写一个Attribute
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class MemberStrAttribute : Attribute
{
public MemberStrAttribute(string str)
{
MemberStr = str;
}
public string MemberStr { get; private set; }
}
- 为枚举扩展一个方法来获取自定义属性的特定值
public static class EnumExtend
{
public static string MemberStr(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
MemberStrAttribute[] attrs =
fi.GetCustomAttributes(typeof(MemberStrAttribute), false) as MemberStrAttribute[];
if (attrs.Length > 0) return attrs[0].MemberStr;
return value.ToString();
}
}
- 使用例程和输出
public enum Test
{
[MemberStr("男的")]
A,
[MemberStr("女的")]
B,
[MemberStr("不男不女的")]
C
}
Test test = Test.A;
Console.WriteLine(test.MemberStr());
test = Test.B;
Console.WriteLine(test.MemberStr());
test = Test.C;
Console.WriteLine(test.MemberStr());
男的
女的
不男不女的