代码之家  ›  专栏  ›  技术社区  ›  Thomas

这段代码中反射的输出类型是什么

  •  0
  • Thomas  · 技术社区  · 5 年前

    public static class ReflectionHelper
    {
        public static List<?> FindType<T>()
        {
            var A =
                from Assemblies in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
                from Types in Assemblies.GetTypes()
                let Attributes = Types.GetCustomAttributes(typeof(T), true)
                where Attributes?.Length > 0
                select new { Type = Types };
    
            var L = A.ToList();
    
            return L;
        }
    }
    

    如果我这样做了:

    foreach (var l in L) { ... }
    

    它可以在find中工作,我可以遍历这些类型,但是我使用的dev环境(Rider)不会提供类型。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Camilo Terevinto Chase R Lewis    5 年前

    IEnumerable<Type> Types;
    

    所以,使用 A.ToList() 提供匿名对象的列表,您无法返回该列表。

    我认为这比使用 select new { Type = Types }; ,您要使用 select Types;

    所以:

    public static List<Type> FindType<T>()
    {
        var types =
            from ssembly in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
            from type in ssembly.GetTypes()
            let attributes = type.GetCustomAttributes(typeof(T), true)
            where attributes?.Length > 0
            select type;
    
        return types.ToList();
    }