gpt4 book ai didi

reflection - 错误处理 "Getting all types that implement an interface with C# 3.0"

转载 作者:行者123 更新时间:2023-12-03 07:42:31 25 4
gpt4 key购买 nike

我在类库中有一个方法,它扫描所有加载的程序集以查找实现某个接口(interface)的类型 la Getting all types that implement an interface

var type = typeof(IMyInteraface);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));

在将类库安装到项目中时,我偶尔会遇到如下 FileNotFoundException:

Could not load file or assembly 'AAA.BBB.CCC, Version=1.2.3.4, Culture=neutral, PublicKeyToken=abcdef0123456789a' or one of its dependencies. The system cannot find the file specified.



我想将 LINQ 查询重写为更安全的错误。出于我的目的,如果无法加载程序集,那么我不必担心尝试加载属于它的任何类型。这是怎么做到的?

最佳答案

您始终可以将 LINQ 分解为嵌套的 foreach循环并添加大量 try-catch block ,并忽略任何给您错误的程序集和任何类型。

var interfaceType = typeof(IMyInterface);
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
try {
foreach (var type in assembly.GetTypes()) {
try {
if (interfaceType.IsAssignableFrom(type))
types.Add(type);
} catch (FileNotFoundException) {}
}
} catch (FileNotFoundException) {}
}

关于reflection - 错误处理 "Getting all types that implement an interface with C# 3.0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7796758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com