zoukankan      html  css  js  c++  java
  • .NET Attribute(特性)的作用与用法——几句话解决Attribute使用的困惑

          本小文旨在言简意赅的介绍.NET中Attribute(特性)的作用与使用,算是对Attribute学习的一个总结吧,不当之处烦请热心网友帮忙斧正,不胜感激!切入正题。

    一点说明

    只介绍作用与使用方法,不深究原理。[其原理可参考MSDN:http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx 等相关文章]

    什么是Attribute?

    Attribute不是别的东西,就是类(貌似废话)。确切的说,它是为C#代码(类型、方法、属性等)提供描述性信息的类!

    Attribute作用是什么?

    两点感触:

    1. 修饰C#代码,对其进行描述或声明;
    2. 运行时通过反射来获取并使用其声明或控制信息。[不是供一般意义上调用或使用的]

    怎么使用Attribute?

    四点感触:

    1. 自定义特性:所有的自定义特性必须直接或间接继承Attribute基类,示例:
      class TestAttribute : Attribute
    2. 实例化:但不是常规意义上的用new实例化它,而是用成对儿的方括号”[”和”]”,示例:
      [Test(Ignore = false)]
    3. 使用位置:必须放在紧挨着被修饰对象的前面。示例:
      [Test(Ignore = false)]
      public static void TestMethod()
    4. 赋值方式:构造函数的参数和类的属性都在括号内赋值,且构造函数实参必须在属性前面。            

    使用小例

    [说明:该示例通过自定义特性TestAttribute来控制(或说明)TestMethod方法是否执行,Ignore=false则执行,else则忽略]     

    View Code
    namespace TestApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                MemberInfo info = typeof(Program).GetMethod("TestMethod");
                TestAttribute attr = (TestAttribute)Attribute.GetCustomAttribute(info, typeof(TestAttribute));
                if (attr != null)
                {
                    if (attr.Ignore)
                    {
                        Console.WriteLine("TestMethod should be ignored. ");
                    }
                    else
                    {
                        Console.WriteLine("TestMethod can be executed/invoked. ");
                        TestMethod();
                    }
                }
    
                Console.Read();
            }
    
            [Test(Ignore = false)]
            public static void TestMethod()
            {
                Console.WriteLine("Message comes from TestMethod.");
            }
        }
    
        class TestAttribute : Attribute
        {
            public TestAttribute()
            {
            }
    
            public bool Ignore { get; set; }
        }
    }

    运行结果

    Ignore=true

    Ignore=false

    篇后语

    这个小例子看似没有任何实用意义,但是在实际应用中对于一类特性,用Attribute的方式来控制是很方便也很容易扩展和维护的,比如我们最常用的Seriablizable、ServiceContract等。

  • 相关阅读:
    linux常用的基础知识
    【AW346】走廊泼水节
    【AW355】异象石
    【POJ3417】闇の連鎖
    【APIO2010】巡逻
    【SDOI2011】消防
    【BJWC2010】次小生成树
    【POJ3613】Cow Relays
    【POJ1734】Sightseeing trip
    【POJ1094】Sorting it all out
  • 原文地址:https://www.cnblogs.com/yuanlb/p/2993849.html
Copyright © 2011-2022 走看看