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
相关推荐
步步为营DotNet44 分钟前
深入剖析.NET 11 中 Microsoft.Extensions.AI 在 AI 驱动后端开发的进阶应用
人工智能·microsoft·.net
林鸿群7 小时前
竞彩网全栈项目实战:克隆与重构,从零构建 Vue3 + .NET 9 现代彩票网站
重构·.net
荔枝吻20 小时前
【系列合集目录】.net开发选型记录
.net
我是唐青枫20 小时前
C#.NET ConcurrentStack<T> 深入解析:无锁栈原理、LIFO 语义与使用边界
网络·c#·.net
荔枝吻1 天前
【AI总结】C#与.NET:一段跨越20年的命名纠葛与共生传奇
开发语言·c#·.net
波波0071 天前
每日一题:请解释 .NET中的内存模型是什么
开发语言·c#·.net
荔枝吻1 天前
【AI总结】【技术选型】 .NET Framework 打包指南:5种主流免费单EXE安装方案对比与推荐
.net·.net framework
light blue bird1 天前
多Tab页签高索引组轴可视化图表
jvm·数据库·.net·桌面端·ai大数据
波波0071 天前
2026 .NET 跨平台桌面开发选型指南:Avalonia vs Uno vs Eto
.net
武藤一雄2 天前
从零构建C# OOP 知识体系
windows·microsoft·c#·.net·.netcore·oop