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
相关推荐
.NET修仙日记1 小时前
2026 .NET 面试八股文:高频题 + 答案 + 原理(面试加分技巧)
面试·职场和发展·.net·.net core·微软技术
黑咩狗夜.cm5 小时前
(aspose.words .net)内容分别固定在一行左右俩端
c#·word·.net
rockey6277 小时前
AScript中一个很有意思的语法
c#·.net·script·eval·expression·动态脚本
时光追逐者12 小时前
2026 年 .NET 客户端常用 MVVM 框架推荐
c#·.net·mvvm·.net core
月昤昽13 小时前
C#实现AutoCAD旋转与直径标注
c#·.net·二次开发·autocad·autocad二次开发
专注VB编程开发20年14 小时前
专业分析python底层调用与按键精灵,ah3等的对比,hookdll,内存加载,调用.net dll
开发语言·javascript·python·microsoft·php·.net
djk888814 小时前
.net swagger api 开启跨域 开启注释
java·前端·.net
我是唐青枫15 小时前
C#.NET YARP 详解:用 ASP.NET Core 打造高性能反向代理网关
c#·.net
OctShop大型商城源码1 天前
.NET线上商城源码_C#商城源码_技术赋能下的电商新生态
开发语言·c#·.net·商城系统源码
柠檬苏打z1 天前
C# SwaggerLoginAuthPlugin 一款给Swagger文档加登录页面的小插件
.net·swagger