如何获取 C# 文件开头加载的命名空间的名称?例如,获取下面的六个命名空间名称。
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Text;
using System.Reflection;
namespace MyNM
{
class MyClass{}
}
最佳答案
这将返回已执行程序集引用的所有程序集。
不过,这不会仅返回特定文件中使用的命名空间 - 这在运行时是不可能的。
var asms = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
foreach (var referencedAssembly in asms)
{
Console.WriteLine(referencedAssembly.Name);
}
不过,从技术上讲,如果您知道包含当前代码的文件的名称,则只需在运行时读取该文件并提取“using”即可。
编辑
执行此操作的方法是:
public static IEnumerable<string> GetUsings()
{
// Gets the file name of the caller
var fileName = new StackTrace(true).GetFrame(1).GetFileName();
// Get the "using" lines and extract and full namespace
return File.ReadAllLines(fileName)
.Select(line => Regex.Match(line, "^\\s*using ([^;]*)"))
.Where(match => match.Success)
.Select(match => match.Groups[1].Value);
}
关于c# - 如何获取开头加载的命名空间的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10526278/