c# - Linq 查询未选择字段列表
问题描述
我有三个 linq 查询,第一个只是得到一个工作正常的程序集类型列表。我遇到的第二个问题。它正在返回0
结果,我不知道为什么。
这是我使用的第一个被重用的查询:
var types = (
from assemblies in AppDomain.CurrentDomain.GetAssemblies()
from type in assemblies.GetTypes()
select type
).ToList();
接下来我有这个返回0
结果的查询,我不知道为什么:
var injectors = (
from type in types
from attrs in type.GetCustomAttributes<InjectAttribute>()
select attrs
).ToList();
第三个查询与第二个查询几乎完全相同,只是它选择了不同的属性。这个有效:
(
from type in types
from attrs in type.GetCustomAttributes<InjectableAttribute>()
where attrs.ProvidedIn == ProvidedIn.Root
select type
).ToList().ForEach(service => {
var injector = injectors.Find(i => i.serviceType == service);
if (injector != null) {
var newService = Activator.CreateInstance(service);
services.Add(newService);
}
})
我不确定为什么第二个查询有效而第三个查询无效...
这是我如何使用这两个:
[Injectable(ProvidedIn = ProvidedIn.Root)]
public class Item { }
public class Test {
[Inject(typeof(Item))] Item item = null;
}
我想要实现的是,如果项目中的一个字段具有[Inject]
用于特定类型的属性,则在 foreach 循环中,然后创建一个实例,否则不要创建一个实例。这是针对可重用类库的,因此注入类型可能会或可能不会在使用该库的项目中使用。如果它没有被使用,我不想创建[Injectable]
.
旁注:创建 3 个单独的 Linq 查询是否最佳,或者我可以将它们组合成一个查询?
解决方案
Inject
应用于成员,而不是类型。要查找其成员具有该属性的类型,您可以使用:
where type.GetMembers()
.SelectAny(mi=>mi.GetCustomAttributes<InjectAttribute>())
.Any()
推荐阅读
- python - 这组代码不断循环和循环。我可以知道如何停止循环吗?
- javascript - 如果我使用了 vm.$watch API,是否需要删除组件 destroy() 上的观察者?
- reactjs - 我在做什么错?,正在使用 npx create-react-app app_name 创建反应应用程序。但我不断收到不寻常的错误
- tableau-api - Tableau中如何根据行中的两个条件过滤数据
- python - Python defaultdict(default) vs dict.get(key, default)
- python - 根据可变时间条件将行拆分为多行
- curl - Libcurl 不会在 cookie.txt 中正确写入 cookie
- windows - 从 Windows 远程备份树莓派 sd 卡
- php - Drupal删除/删除内容中包含特定单词的所有页面
- python-3.x - 如何检查一组元组中的一个元组切片是否在另一组元组中?