好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

.NET Attribute(特性)的作用与用法

.NET Attribute(特性)的作用与用法

.NET Attribute(特性)的作用与用法——几句话解决Attribute使用的困惑

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

一点说明

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

什么是Attribute?

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

Attribute作用是什么?

两点感触:

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

怎么使用Attribute?

四点感触:

自定义特性 :所有的自定义特性必须直接或间接继承Attribute基类,示例:

 class  TestAttribute : Attribute

实例化 :但不是常规意义上的用new实例化它,而是用成对儿的方括号”[”和”]”,示例:

[Test(Ignore =  false )]

使用位置 :必须放在紧挨着被修饰对象的前面。示例:

[Test(Ignore =  false  )]
public static void TestMethod()

赋值方式 :构造函数的参数和类的属性都在括号内赋值,且构造函数实参必须在属性前面。             

使用小例

[说明:该示例通过自定义特性TestAttribute来控制(或说明)TestMethod方法是否执行,Ignore=true则执行,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等。

 

 

分类:  .NET(C#)

标签:  C#Attribute ,  特性

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于.NET Attribute(特性)的作用与用法的详细内容...

  阅读:28次