VB.NET 取当前项目根命名空间

VB.NET 取当前项目根命名空间

在VB.NET中,可以使用反射来获取当前程序集的入口点类型(通常是模块或者主类),然后从这个类型的Assembly信息中获取定义它的程序集的根命名空间。以下是一个获取当前项目根命名空间的方法示例:

请注意,这个方法假设您的项目具有一个AssemblyTitleAttribute,并且这个Title属性反映了项目的根命名空间。如果没有设置AssemblyTitle,或者设置的方式不符合预期,那么可能需要调整代码来适应具体的项目结构。

vbnet 复制代码
  Dim currentNamespace As String = GetCurrentRootNamespace()
        MsgBox("当前项目根命名空间:" & currentNamespace)

    Function GetCurrentRootNamespace() As String
        '取根命名空间

        ' 获取入口点类型
        Dim assembly As Assembly = Assembly.GetExecutingAssembly()
        Dim entryType As Type = Assembly.GetEntryAssembly().GetTypes()(0)

        ' 获取当前程序集
        assembly = Assembly.GetAssembly(entryType)

        ' 获取当前程序集的属性
        Dim attributes As AssemblyTitleAttribute() = assembly.GetCustomAttributes(GetType(AssemblyTitleAttribute), False)

        ' 如果定义了AssemblyTitleAttribute,则使用它的Title作为根命名空间
        If attributes.Length > 0 Then
            Dim title As String = attributes(0).Title
            Dim nsIndex As Integer = title.IndexOf(".")
            If nsIndex > 0 Then
                Return title.Substring(0, nsIndex)
            End If
        End If

        ' 如果没有定义AssemblyTitleAttribute,则从入口点类型的全名中提取根命名空间
        Dim fullName As String = entryType.FullName
        If fullName IsNot Nothing Then
            Dim nsIndex As Integer = fullName.IndexOf(".")
            If nsIndex > 0 Then
                Return fullName.Substring(0, nsIndex)
            End If
        End If

        Return String.Empty
    End Function
相关推荐
界面开发小八哥14 小时前
界面控件DevExpress Blazor v26.1新版亮点 - TreeList & 数据编辑器
javascript·编辑器·.net·界面控件·blazor·devexpress·用户界面
rockey6271 天前
C#脚本引擎之AScript与Flee对比
c#·.net·script·eval·动态脚本
海盗12341 天前
微软技术周报 · 2026-08-11~2026-08-18
人工智能·microsoft·.net
Leinwin2 天前
微软MAI-Code-1.1-Flash技术解读:Token效率提升25%,CLI与.NET全面升级
microsoft·.net
慧都小妮子2 天前
C# 实现AI合同审查:从读取、风险标注到批量签发
ai·自然语言处理·c#·.net·办公自动化·ai合同审查·文档ai代理
唐青枫5 天前
别把 ImmutableArray 当成只读 List:C#.NET 不可变数组深入详解
c#·.net
微小冷6 天前
海康威视相机C#二次开发环境配置
数码相机·c#·.net·海康威视·相机开发
唐青枫6 天前
别只会解析参数:C#.NET Spectre.Console.Cli 命令行工具实战详解
c#·.net
rockey6277 天前
基于AScript的Lua脚本语言发布啦
c#·.net·lua·script·动态脚本
半亩码田7 天前
【.NET新特性·第11篇】C# 14 字段属性:告别手写 backing field
java·c#·.net