首先创建一个枚举类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute
{
public enum UserState
{
/// <summary>
/// 正常
/// </summary>
[Remark("正常")]
Normal = 0,
/// <summary>
/// 冻结
/// </summary>
[Remark("冻结")]
Frozen = 1,
/// <summary>
/// 删除
/// </summary>
[Remark("删除")]
Deleted = 2
}
}
使用枚举类生成一个对象,并对枚举中每一项进行赋值;这样操作比较麻烦而且不灵活。
static void Main(string[] args)
{
UserState userState = UserState.Frozen;
if (userState == UserState.Normal)
{
Console.WriteLine("正常");
}
else if (userState == UserState.Frozen)
{
Console.WriteLine("冻结");
}
}
以上是通过类对象的实现。下面通过特性来操作。首先创建一个特性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute
{
[AttributeUsage(AttributeTargets.Field)]
public class RemarkAttribute:Attribute
{
/// <summary>
/// 状态特性
/// </summary>
/// <param name="remark"></param>
public RemarkAttribute(string remark)
{
this.Remark = remark;
}
public string Remark { get;private set; }
}
}
创建一个调用特性的类AtrributeInvoke.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute
{
public class AttributeInvoke
{
/// <summary>
/// 接收一个枚举对象
/// </summary>
/// <param name="userState"></param>
/// <returns></returns>
public string GetRemark(UserState userState)
{
Type type = userState.GetType(); //能过枚举对象获取类型
var fileId = type.GetField(userState.ToString()); //从枚举对象中获取字段
if (fileId .IsDefined(typeof(RemarkAttribute),true)) //判断字段是否为特性
{
RemarkAttribute remarkAttribute = (RemarkAttribute)fileId.GetCustomAttribute(typeof(RemarkAttribute), true);
return remarkAttribute.Remark; //如果字段是特性则调用特性中的Remark
}
else
{
return userState.ToString();
}
}
}
}
在Main函数中进行实例化并调用
static void Main(string[] args)
{
UserState userState = UserState.Frozen;
AttributeInvoke attributeInvoke = new AttributeInvoke();
Console.WriteLine(attributeInvoke.GetRemark(userState));
}
通过特性操作的方法也能实现同样的功能