首页 > 解决方案 > 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 查询是否最佳,或者我可以将它们组合成一个查询?

标签: c#linq

解决方案


Inject应用于成员,而不是类型。要查找其成员具有该属性的类型,您可以使用:

where type.GetMembers()
          .SelectAny(mi=>mi.GetCustomAttributes<InjectAttribute>())
          .Any()

推荐阅读