c# - 如何获取开头加载的命名空间的名称

标签 c# namespaces

如何获取 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/

相关文章:

c# - 如何在更改值后在运行时保存 ScriptableObject

c# - 将值从 java 脚本传递到隐藏字段不起作用

c# - 在嵌入式代码中使用动态类型的 c# 变量

c# - MVVM应用程序中的工具箱设计

c++ - 跨多个文件定义命名空间

reflection - 在运行时导入脚本

c++ - 在模板参数上使用隐式命名空间

c# - 如何测试类的实例是否为特定泛型类型?

c++ - 为什么每个人都使用 unanchored 命名空间声明(即 std::not::std::)?

c++ - 跨不同命名空间的友元类。那可能吗