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
相关推荐
Eiceblue2 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
步、步、为营4 小时前
.net开源库SignalR
开源·.net
追逐时光者6 小时前
一款开源免费、通用的 WPF 主题控件包
后端·.net
步、步、为营8 小时前
.net开源物联网项目IoTSharp
物联网·开源·.net
百锦再9 小时前
.Net配置文件appsetting.json的几种读取方法
chrome·json·.net·依赖注入·appsetting·web.config
ChaITSimpleLove14 小时前
.NET9 实现排序算法(MergeSortTest 和 QuickSortTest)性能测试
算法·排序算法·.net·benchmarkdotnet·datadog.trace
军训猫猫头2 天前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
追逐时光者2 天前
C#/.NET/.NET Core优秀项目和框架2025年6月简报
后端·.net
步、步、为营2 天前
.net审计库:EntityFrameworkCore.Audit
数据库·oracle·.net