remark
Remark特性扩展
1.假设程序中有一个枚举类型UserState:
public enum UserState
{
//通过增加特性,扩展Remake
/// <summary>
/// 正常
/// </summary>
[Remark("正常")]
Normal =0,
/// <summary>
///冻结
/// </summary>
[Remark("冻结")]
Frezeen =2,
/// <summary>
/// 删除
/// </summary>
Delete=4
}
我们想要在程序中使用的是枚举值,但是提供给UI界面的是另外的字符串,就可以用到特性加扩展方法来实现。
2.增加一个RemakeAttribute特性
[attributeusage(AttributeTargets.Enum | AttributeTargets.field)]
public class RemarkAttribute:Attribute
{
private string _Remake=null;
public RemarkAttribute(string remake)
{
this._Remake = remake;
}
public string GetRemark()
{
return this._Remake;
}
}
3.增加一个扩展方法AttributeExtension
public static string GetRemark(this Enum value)
{
Type type = value.GetType();
FieldInfo field = type.GetField(value.ToString());
if (field.Isdefined(typeof(RemarkAttribute), true))
{
RemarkAttribute attribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute), true);
return attribute.GetRemark();
}
else
{
return value.ToString();
}
}
4.前端使用:
try
{
UserState userState = UserState.Normal;
console.WriteLine(userState.GetRemark());
Console.WriteLine(UserState.Frezeen.GetRemark());
Console.WriteLine(UserState.Delete.GetRemark());
Console.Read();
}
catch (Exception)
{
throw;
}