C# System.ComponentModel.Composition中的Export和Import特性標籤的簡單使用。

使用Export和Import特性標籤主要是爲了讓程序進行解耦。部分代碼借鑑自https://blog.csdn.net/a1037949156/article/details/79535129

如有侵權請聯繫,即刻刪除。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

 
using System.Reflection;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {

            Go go = new Go();
            //獲取當前執行的程序集中所有的標有特性標籤的代碼段
            AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            //將所有Export特性標籤存放進組件容器中(其實是一個數組裏面)
            CompositionContainer container = new CompositionContainer(catalog);

            //找到所傳入對象中所有擁有Import特性標籤的屬性,並在組件容器的數組中找到與這些屬性匹配的Export特性標籤所標註的類,然後進行實例化並給這些屬性賦值。
            //簡而言之,就是找到與Import對應的Export所標註的類,並用這個類的實例來給Import所標註的屬性賦值,用於解耦。
            container.ComposeParts(go);
            go.test.show();
        }
    }
    //定義一個測試接口
    interface ITest
    {
        void show();

    }

    //Export出去的類型和名稱都要和Import標註的屬性匹配,類型可以寫ITest, 也可以寫Test
    [Export("wakaka", typeof(ITest))]
    class Test : ITest
    {
        public void show()
        {
            Console.WriteLine("OK");
        }
    }

    class Go
    {
        [Import("wakaka")]
        public ITest test { get; set; }
    }
}

 

 

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