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; }
    }
}

 

 

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