.NET无处不在的特性(Attribute)

    我们在开发中,用到特性的地方很多,比如控制器中的HttpPost特性,属性的序列号特性Serializable,还有验证特性Authorize等。今天我们来探究一下特性(Attribute),并简单定义一个自己的特性。由于篇幅问题,本文章分为两篇,第一篇为探究,第二篇自定义特性(在自定义特性中将会一步一教你定义,并且做重构优化)。

特性探究

    特性也是.NET的重要一组件,首先我们看官网如何说明特性的“ 使用特性,可以有效地将元数据或声明性信息与代码(程序集、类型、方法、属性等)相关联。将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性。 ”。有两个关键点,可以将元数据或声明在“程序集、类型、方法、属性”中相关联,并且可以通过反射查询特性。特性按运行时生效形式分2类:一是编译器生效时(obslote); 二类是运行时生效的,这类使用比较频繁,我们主要介绍这类。下面我们简单定义一个特性,并通过IL反编译工具查看它具体做了什么?

    这里我们自定义了一个空特性,然后我们定义一个客户类,在客户类使用特性,然后看会不会对客户类产生影响。从下面例子可以看出,特性可以使用在程序集、类型、方法、属性;自定义特性的也很简单,先定义一个类,然后继承Attribute就可以了。

//这里我们自定义了一个特性
public class AttributeTest: Attribute
{
}
//使用特性
[AttributeTest]
public class Customer
 {
    [AttributeTest]
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public int age { get; set; }
    [AttributeTest]
    public void getname([AttributeTest] string name)
    {
        Console.WriteLine($"your name is {name}!");
    }
}
//调用Customer类
static void  Main(string[] args)
{
      Customer customer = new Customer()
      {
                id = 2,
                name = "张学友",
                age = 52,
                email = "zxy@net.cn"
      };
       Console.WriteLine($"your name is {customer.name}");
}

调用后正常调用,没有啥问题。那我们看看IL反编译的结果:

 

 

除了custom这个对象东东,没有啥了,也不影响代码的使用。可以看出空壳的特性没有任何效果,只有标记的作用。

那么我们如何调用特性呢?微软官网说了,使用反射。我们用上面的例子简单的调用一下,在特性类加上一个方法和属性。

    public class AttributeTest: Attribute
    {
        public string content { get; set; }
        public void showcontent()
        {
            Console.WriteLine("这是特性的方法!");
        }
    }
static void  Main(string[] args)
{
  //首先用反射判断这个类中是否有这个特性
   if(typeof(Customer).IsDefined(typeof(AttributeTest),true))
   {
     Console.WriteLine($"{nameof(Customer)}的特性是:Attributetest");
     //反射实例化特性     
     var Attributefuns=typeof(Customer).GetCustomAttributes<AttributeTest>();
     foreach (var item in Attributefuns)
     {
         item.showcontent();
     }
 }
}

结果如下,通过反射调用了特性的方法。

 

 

鸣谢:

https://mp.weixin.qq.com/s/C3S0xGi9t7kEF7qOtSqMaw

posted @   春光牛牛  阅读(103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示