日落20191001001 - C#基礎之條件Attribute的減法藝術

環境

系統:Windows 10
引擎:VS2017

目的

通過製作自定義的條件Attribute類及預定義參數,降低元數據的無效信息量。

實例

#define TEST_1
//#define TEST_2

using System;
using System.Diagnostics;

namespace ConditionalAttributeTest
{
    #region 特性類
    [Conditional("TEST_1")] // 只有定義了TEST_1,纔會應用於目標元素,並在元數據生成此特性信息。
    public sealed class Cond_1_Attribute : Attribute { }

    [Conditional("TEST_2")] // 只有定義了TEST_2,纔會應用於目標元素,並在元數據生成此特性信息。
    public sealed class Cond_2_Attribute : Attribute { }

    [Conditional("TEST_1")][Conditional("TEST_2")] // 當定義了TEST_1或TEST_2時,就會應用於目標元素,並在元數據生成此特性信息。
    public sealed class Cond_3_Attribute : Attribute { }
    #endregion

    #region 測試類
    [Cond_1_][Cond_2_][Cond_3_]
    public sealed class TargetType {}
    #endregion

    class Program
    {
        private static void ShowResult(Type targetType, Type attrType)
        {
            Console.WriteLine("{0} is {1}applied to {2} type.", attrType, Attribute.IsDefined(targetType, attrType) ? "" : "not ", targetType);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Type targetType = typeof(TargetType);
            Type[] attrTypes =
            {
                typeof(Cond_1_Attribute),
                typeof(Cond_2_Attribute),
                typeof(Cond_3_Attribute),
            };

            foreach (Type attrType in attrTypes)
            {
                Program.ShowResult(targetType, attrType);
            }
        }
    }
}

結果

ConditionalAttributeTest.Cond_1_Attribute is applied to ConditionalAttributeTest.TargetType type.

ConditionalAttributeTest.Cond_2_Attribute is not applied to ConditionalAttributeTest.TargetType type.

ConditionalAttributeTest.Cond_3_Attribute is applied to ConditionalAttributeTest.TargetType type.

以上簡單回顧。

參考資料:

《CLR via C#(第3版)》第18.7節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章