Finding all Namespaces in an assembly using Reflection (DotNET)

后端 未结 6 1067
滥情空心
滥情空心 2020-11-30 09:51

I\'ve got an assembly (loaded as ReflectionOnly) and I want to find all the namespaces in this assembly so I can convert them into \"using\" (\"Imports\" in VB) statements f

6条回答
  •  时光说笑
    2020-11-30 10:33

    public static void Main() {
    
        var assembly = ...;
    
        Console.Write(CreateUsings(FilterToTopLevel(GetNamespaces(assembly))));
    }
    
    private static string CreateUsings(IEnumerable namespaces) {
        return namespaces.Aggregate(String.Empty,
                                    (u, n) => u + "using " + n + ";" + Environment.NewLine);
    }
    
    private static IEnumerable FilterToTopLevel(IEnumerable namespaces) {
        return namespaces.Select(n => n.Split('.').First()).Distinct();
    }
    
    private static IEnumerable GetNamespaces(Assembly assembly) {
        return (assembly.GetTypes().Select(t => t.Namespace)
                .Where(n => !String.IsNullOrEmpty(n))
                .Distinct());
    }
    

提交回复
热议问题