天天看點

C#中的特性

   C#中的特性,允許向程式的程式集增加中繼資料,用于儲存程式結構資訊。

1.Obsolete

    Obsolete特性标記方法已被棄用。并在代碼編譯時,顯示警告資訊。

[Obsolete("該方法已被棄用")]
static void OldMethod()
{
     Console.WriteLine("OldMethod");
}
           

2.Conditional

   Conditional特性,使用或取消方法的調用,執行依賴于指定的預處理辨別符。

[Conditional("TEST")]
static void TestMethod()
{
    Console.WriteLine("TestMethod");
}
           

當在定義了#define TEST時,該方法被調用,否則不調用。一般用于調試資訊的輸出。

3.DebuggerStepThrough

   調試代碼時,告訴調試器不要進入某些方法。當确定某些方法沒有錯誤的時候,使用該特性。

[DebuggerStepThrough]
static void TestMethod2()
{
     Console.WriteLine("TestMethod2");
}
           

4.調用者資訊特性

   CallerFilePath 擷取調用該方法的檔案路徑

   CallerLineNumber 擷取調用該方法的源檔案的行号

   CallerMemberName 擷取調用該方法的方法名

using System;
using System.Runtime.CompilerServices;

namespace CSharpTest
{
    class Program
    {
        //調用者資訊特性
        static void PrintStr(string str, [CallerFilePath]string file = "", [CallerLineNumber]int line = 0,
            [CallerMemberName]string method = "")
        {
            Console.WriteLine(str);
            Console.WriteLine("檔案名:" + file);
            Console.WriteLine("行号: " + line);
            Console.WriteLine("方法名: " + method);
        }

        static void Main(string[] args)
        {
            PrintStr("Hello,April");
            Console.ReadKey();
        }
    }
}
           

運作結果

C#中的特性

5.自定義特性

   自定義特性類時,需要遵守一些規則:

  •    類名稱以Attribute結尾
  •    繼承System.Attribute
  •    一般情況下聲明為sesealed,不能被繼承
  •    表示目标結構的狀态(包含字段及屬性,一般不定義方法)   
using System;

namespace CSharpTest
{
    [Test("自定義特性類", 1.2)]
    class Program
    {
        [AttributeUsage(AttributeTargets.Class)] //該特性類适用範圍
        sealed class TestAttribute : Attribute
        {
            public string Description { get; set; }
            public double Version { get; set; }

            public TestAttribute(string description, double version)
            {
                this.Description = description;
                this.Version = version;
            }
        }

        static void Main(string[] args)
        {
            Type type = typeof(Program);
            object[] array = type.GetCustomAttributes(false);
            TestAttribute attr = array[0] as TestAttribute;
            Console.WriteLine("Description: " + attr.Description);
            Console.WriteLine("Version: " + attr.Version);

            Console.ReadKey();
        }
    }
}
           

 運作結果

C#中的特性