Dav*_*ten 20 c# vb.net reflection assemblies namespaces
我有一个程序集(作为ReflectionOnly加载),我想找到这个程序集中的所有命名空间,所以我可以将它们转换为自动生成的源代码文件模板的"using"(VB中的"Imports")语句.
理想情况下,我只想将自己限制在顶级命名空间,而不是:
using System;
using System.Collections;
using System.Collections.Generic;
Run Code Online (Sandbox Code Playgroud)
你只会得到:
using System;
Run Code Online (Sandbox Code Playgroud)
我注意到System.Type类上有一个Namespace属性,但有没有更好的方法来收集程序集内的Namespaces,它不涉及迭代所有类型并剔除重复的命名空间字符串?
大卫,很有责任
Jon*_*eet 36
不,这没有捷径,虽然LINQ使它相对容易.例如,在C#中,原始的"名称空间集"将是:
var namespaces = assembly.GetTypes()
.Select(t => t.Namespace)
.Distinct();
Run Code Online (Sandbox Code Playgroud)
要获得顶级命名空间,您应该编写一个方法:
var topLevel = assembly.GetTypes()
.Select(t => GetTopLevelNamespace(t))
.Distinct();
...
static string GetTopLevelNamespace(Type t)
{
string ns = t.Namespace ?? "";
int firstDot = ns.IndexOf('.');
return firstDot == -1 ? ns : ns.Substring(0, firstDot);
}
Run Code Online (Sandbox Code Playgroud)
我很感兴趣为什么你只需要顶级命名空间......但它似乎是一个奇怪的约束.
归档时间: |
|
查看次数: |
16816 次 |
最近记录: |