文章目录
- 前言
- 一、特性的基础语法及本质
- 二、特性的标记
- 三、特性调用
- 四、特性的使用场景
- 总结
前言
MVC等框架,特性被广泛应用,实际开发中也经常使用特性,但是大部分人没有自定义过特性,缺乏对特性的本质理解;本文对特性做全方位的解析,让广大小伙伴的武器库新增一利器;
一、特性的基础语法及本质
- 特性实际就是一个类,只是这个这个类必须继承Attribute抽象类,其他类的一些特性类都可以
- 特性是可以被修饰的,用[AttributeUsage]修饰,AttributeUsage本身也是一个特性;AttributeUsage可以标记当前的特性生效的场景,可以是类/属性/字段/方法/等等
代码案例
/// <summary>
/// 自定义特性
/// </summary>
[AttributeUsage(AttributeTargets.All)]//特性修饰,可以不显示声明
//[AttributeUsage(AttributeTargets.Class| AttributeTargets.Method| AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class CustomAttribute:Attribute
{
/// <summary>
/// 私有变量
/// </summary>
private int _age;
/// <summary>
/// 构造函数
/// </summary>
public CustomAttribute() {
}
/// <summary>
/// 带参数的构造函数
/// </summary>
public CustomAttribute(int age)
{
_age = age;
}
/// <summary>
/// 属性
/// </summary>
public string name { get; set; }
/// <summary>
/// 方法
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public bool method(object value) {
return value.ToString() == name;
}
}
二、特性的标记
特性标记比较简单,注意事项都写在注释里了
/// <summary>
/// 测试类
/// </summary>
public class CustomModel
{
[CustomAttribute]//标记特性
public int id { get; set; }
[Custom]//和上面等效,如果特性是以Attribute结尾,可以省略
public string student { get; set; }
[Custom(3)]//传入构造函数
public string No { get; set; }
[Custom(name ="text")]//给特性的属性赋值,属性赋值和构造函数赋值,语法是不同的,属性赋值要 xxx=xxx
public string notes { get; set; }
[Custom(4,name = "text")]//构造函数和属性赋值混用,构造函数要在前面
public string remark { get; set; }
}
三.特性调用
特性只能通过反射调用,不通过反射单独调用,特性标记不产生任何作用;特性可以类比成配置文件,写入配置文件的信息,不调用不起任何作用,特性只是要通过反射调用罢了;
public static class CustomExtend {
/// <summary>
/// 用扩展的方式调用特性,也可以写平常方法
/// </summary>
/// <param name="model"></param>
public static void CustomExcute(this CustomModel model)
{
//变量所有的属性
foreach (var item in typeof(CustomModel).GetProperties())
{
//判断属性中是否用CustomAttribute标记
if (item.IsDefined(typeof(CustomAttribute), true))
{
//当前属性的所有CustomAttribute特性
foreach (var att in item.GetCustomAttributes(typeof(CustomAttribute), true))
{
//这里就是特性[CustomAttribute]的类实例,可以对类进行任何操作
CustomAttribute customAttribute = (CustomAttribute)att;
Console.WriteLine(customAttribute.name);//找到属性
Console.WriteLine(customAttribute.method(item.GetValue(model)));//找到方法
}
}
}
}
}
四.特性的使用场景
特性是在不破坏类的前提下,对类的补充;特性非常灵活而且使用面相当广泛;
- 注释,反射是无法获取类属性的注释的,可以把注释写在特性里,调用特性就能找到注释,这其实是MVC的[Description]特性
- 验证,电话或者地址的验证,写好特性标记在需要的类属性即可
- 判断,字段长度或者是否为空等情况,也可以通过特性
- 过滤,某些情况不允许使用本函数,通过特性实现,这其实是MVC的过滤器
- 映射,将一个类映射到另一个类,可以在特性标记目标类的属性名称
总结
想象力有多大,特性就有多大;特性在框架中是一个非常重要的部分,这个技术不能不掌握;如果不能装X,代码又有什么意义呢,特性是装X必不可少的利器,诸位小伙伴一定要掌握啊;我还要其他关于特性的文章,欢迎指正;