首页 技术 正文
技术 2022年11月7日
0 收藏 310 点赞 401 浏览 1349 个字

我们已经成功的达到了目标,大量减少了if else。

不过在园子里面的文章大多,用的是Import、ImportMany。So,修改主函数。

using IPart;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;namespace meftest
{
class Program
{
[ImportMany]
private IEnumerable<Lazy<IFileHandler, IPatMetadata>> fileHandlers;//警告,说没有赋值过。不用理会,MEF会自己导入的。
static void Main(string[] args)
{
//模拟数据。
string[] files = new string[] {
@"c:\xxoo\xxoo.txt",
@"c:\xxoo\ooxx.doc",
@"d:\测试目录\mm.jpg",
@"e:\电影\天海翼.avi",
};
Program p = new Program();
p.Compose();
foreach (var file in files)
{
string ext = System.IO.Path.GetExtension(file).ToLower();
var export = p.fileHandlers.SingleOrDefault(o => o.Metadata.Extension == ext);//根据扩展名,也就是元数据来找到对应的处理实例
if (export != null)
export.Value.Process(file);
}
Console.ReadLine();
}
private void Compose()
{
//AssemblyCatalog 目录的一种,表示在程序集中搜索
var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly);//此处这一句实际上没啥用,因为此程序集下没有任何我们需要的实例(各种handler)
//在某个目录下的dll中搜索。
var directoryCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog);//聚合目录包含有2种搜索方式
var container = new CompositionContainer(aggregateCatalog);
container.ComposeParts(this);//将部件组合在一起。意思就是将所有Export的部件,装配到this实例中标记为Import、ImportMany的属性上。
}
}
}

不过这里有一个要注意的地方,不能在主函数内部来进行装配。原因如下图。

MEF入门之不求甚解,但力求简单能讲明白(五)运行结果:MEF入门之不求甚解,但力求简单能讲明白(五)

ok,现在MEF你已经入门了,再看大神们的文章心里也有点底了。本系列到此结束。

下一篇: Yii2初谈
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902