特点: 特性典型的AOP编程思想,可以在不破坏封装的前提下,动态增加功能,额外信息, 是一个类,可以标记在别的元素上面,标记后对编译/运行其实都没有影响,只是生成了一些内部的元素,普通的方式找不到但可以通过反射来获取并使用
特性对于程序来说一切都是假象,程序编写中无法访问到,对程序也没影响,我们通过反编译发现,特性被编译成内部元素,但是代码无法访问到,而是在matadata中记录 而反射可以动态读取并使用meatada,基于反射,就可以在程序中去识别并使用特性
对于一个字段或类上需要多个属性的,我们应该采用面向切面编程的思想来写特性的结构,采用继承的关系,这样我们可以更方便的操作; 对于不是多个判断的我们不需要采用继承的结构,一般解析特性需要:
- 获取类型 Type type = eValue.GetType();
- 获取我们需要的字段或属性... foreach (var item in type.GetProperties())
- 判断是否存在此特性 if (item.IsDefined(typeof(AbstractValidateAttribute), true))
- 找到上面的特 多个(var attributeArray = item.GetCustomAttributes(typeof(AbstractValidateAttribute), true);foreach (AbstractValidateAttribute item1 in attributeArray) )单个( RemarkAttribute remarkAttribute =(RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute));)
如果我们想要自定义特性都要继承自Attribute类
简单示例代码如下:
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
public class RemarkAttribute : Attribute
{
private string _Remark;
public RemarkAttribute(string remark)
{
_Remark = remark;
}
public string Remark { get { return _Remark; } }
}
public static class RemarkExtend
{
public static string GetRemark(this Enum eValue)
{
try
{
Type type = eValue.GetType();
FieldInfo field = type.GetField(eValue.ToString());
RemarkAttribute remarkAttribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute));
if (remarkAttribute == null)
{
return field.ToString();
}
else
return remarkAttribute.Remark;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
public enum UserState
{
/// <summary>
/// 正常
/// </summary>
[Remark("正常")]
Normal = 0,
/// <summary>
/// 冻结
/// </summary>
[Remark("冻结")]
Frozen = 1,
/// <summary>
/// 删除
/// </summary>
[Remark("删除")]
Delete = 2
}