Never give up

C#中Attribute的用法

上一篇 / 下一篇  2016-12-05 11:24:38

Attribute类的用法:
using System;
using System.Reflection;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            PrintAuthorInfo(typeof(FirstClass));
            PrintAuthorInfo(typeof(SecondClass));
            PrintAuthorInfo(typeof(ThirdClass));
            PrintAuthorInfo(typeof(ForthClass));
            Console.ReadKey();
        }

        private static void PrintAuthorInfo(System.Type t)
        {
            System.Console.WriteLine("\n Type is System.Type Object is:{0}", t);
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  //反射获得用户自定义属性  

            foreach (System.Attribute attr in attrs)
            {
                if (attr is Author)
                {
                    Author a = (Author)attr;
                    System.Console.WriteLine("   Name:{0}, Version: {1:f}", a.GetName(), a.version);
                }
            }
        }
    }



    [System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)
    ]//自定义特性类(应用特性的程序元素(是类或结构),程序元素可以指定多个特性)  
    public class Author : System.Attribute
    {
        string name;
        public double version;

        public Author(string name)
        {
            this.name = name;
            version = 1.0;  // Default value  
        }

        public string GetName()
        {
            return name;
        }
    }

    [Author("H. Ackerman")]
    public class FirstClass
    {
        // ...  
    }

    // No Author attribute  
    public class SecondClass
    {
        // ...  
    }

    [Author("H. Ackerman"), Author("M. Knott", version = 2.0), Author("Kathleen")]
    public class ThirdClass
    {
        //程序元素可以指定多个特性  
    }
    
    
    [Author("K.Mac", version = 2.0)]
    public class ForthClass
    {
        //程序元素可以指定多个特性  
    }


}
其中.Net 框架提供了三种预定义特性:
  • AttributeUsage
  • Conditional
  • Obsolete

AttributeUsage

预定义特性 AttributeUsage 描述了如何使用一个自定义特性类。它规定了特性可应用到的项目的类型。

规定该特性的语法如下:

[AttributeUsage(
   validon,
   AllowMultiple=allowmultiple,
   Inherited=inherited
)]
其中:
  • 参数 validon 规定特性可被放置的语言元素。它是枚举器 AttributeTargets 的值的组合。默认值是 AttributeTargets.All
  • 参数 allowmultiple(可选的)为该特性的 AllowMultiple 属性(property)提供一个布尔值。如果为 true,则该特性是多用的。默认值是 false(单用的)。
  • 参数 inherited(可选的)为该特性的 Inherited 属性(property)提供一个布尔值。如果为 true,则该特性可被派生类继承。默认值是 false(不被继承)。

例如:

[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property, 
AllowMultiple = true)]

Conditional

这个预定义特性标记了一个条件方法,其执行依赖于它顶的预处理标识符。

它会引起方法调用的条件编译,取决于指定的值,比如 Debug 或 Trace。例如,当调试代码时显示变量的值。

规定该特性的语法如下:

[Conditional(
   conditionalSymbol
)]

例如:

[Conditional("DEBUG")]

下面的实例演示了该特性:

#define DEBUG
using System;
using System.Diagnostics;
public class Myclass
{
    [Conditional("DEBUG")]
    public static void Message(string msg)
    {
        Console.WriteLine(msg);
    }
}
class Test
{
    static void function1()
    {
        Myclass.Message("In Function 1.");
        function2();
    }
    static void function2()
    {
        Myclass.Message("In Function 2.");
    }
    public static void Main()
    {
        Myclass.Message("In Main function.");
        function1();
        Console.ReadKey();
    }
}

当上面的代码被编译和执行时,它会产生下列结果:

In Main function
In Function 1
In Function 2

Obsolete

这个预定义特性标记了不应被使用的程序实体。它可以让您通知编译器丢弃某个特定的目标元素。例如,当一个新方法被用在一个类中,但是您仍然想要保持类中的旧方法,您可以通过显示一个应该使用新方法,而不是旧方法的消息,来把它标记为 obsolete(过时的)。

规定该特性的语法如下:

[Obsolete(
   message
)]
[Obsolete(
   message,
   iserror
)]

其中:

  • 参数 message,是一个字符串,描述项目为什么过时的原因以及该替代使用什么。
  • 参数 iserror,是一个布尔值。如果该值为 true,编译器应把该项目的使用当作一个错误。默认值是 false(编译器生成一个警告)。

下面的实例演示了该特性:

using System;
public class MyClass
{
   [Obsolete("Don't use OldMethod, use NewMethod instead", true)]
   static void OldMethod()
   { 
      Console.WriteLine("It is the old method");
   }
   static void NewMethod()
   { 
      Console.WriteLine("It is the new method"); 
   }
   public static void Main()
   {
      OldMethod();
   }
}

当您尝试编译该程序时,编译器会给出一个错误消息说明:

 Don't use OldMethod, use NewMethod instead

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-27  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 21532
  • 日志数: 14
  • 建立时间: 2016-10-17
  • 更新时间: 2017-06-28

RSS订阅

Open Toolbar