1. 程式人生 > >C#特性(Attribute)之預定義特性(Conditional)

C#特性(Attribute)之預定義特性(Conditional)

特性(Attribute)是用於在執行時傳遞程式中各種元資料(類、方法、結構、列舉、元件)的行為性宣告標籤。

特性用於新增元資料,如編譯器指令和註釋、描述、方法、類等其他資訊。

.NET 框架提供了兩種型別的特性:預定義特性和自定義特性。

Net 框架提供了三種預定義特性:

  • Conditional  這個預定義特性標記了一個條件方法,其執行依賴於他的預處理識別符號。

//可以註釋#define指令看看效果。

#define TRACE_ON
using 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