C#特性(Attribute)之预定义特性(Conditional)

来源:互联网 发布:人工智能权威杂志 编辑:程序博客网 时间:2024/05/01 07:55

特性(Attribute)是用于在运行时传递程序中各种元数据(类、方法、结构、枚举、组件)的行为性声明标签。

特性用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。

.NET 框架提供了两种类型的特性:预定义特性和自定义特性。

Net 框架提供了三种预定义特性:

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

//可以注释#define指令看看效果。

#define TRACE_ONusing System;using System.Diagnostics;public class Trace{    [Conditional("TRACE_ON")]    public static void Msg(string msg)    {        Console.WriteLine(msg);    }}public class ProgramClass{    static void Main()    {        Trace.Msg("Now in Main...");        Console.WriteLine("Done.");        Console.ReadKey();    }}

  • Obsolete   这个预定义标记了不应被使用的程序实体。

         参数 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");    }     [Obsolete("Don't use OldMethod, use NewMethod instead", false)]    static void NewMethod()    {        Console.WriteLine("It is the new method");    }    public static void Main()    {        OldMethod();        NewMethod();        Console.ReadKey();    }}

        AttributeUsage 

http://www.cnblogs.com/stzyw/archive/2005/10/07/249693.html

http://www.w3cschool.cc/csharp/csharp-attribute.html














0 0