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
相关推荐
步步为营DotNet2 小时前
深入理解ASP.NET Core Middleware:构建高效Web应用的关键组件
中间件·asp.net·.net
我是唐青枫2 小时前
C#.NET SignalR 深入解析:实时通信、Hub 与连接管理实战
开发语言·c#·.net
波波0073 小时前
每日一题:什么是.NET中的线程池?
面试·.net
落叶@Henry5 小时前
.NET实现每天8小时的计划周期安排分割逻辑
windows·.net
军训猫猫头5 小时前
5.正弦波生成器:支持连续相位与可控重置 C# + WPF 完整示例
c#·.net·wpf
专注VB编程开发20年5 小时前
Windows 依赖「注册表 + API+COM」的模式,linux全是读文件
linux·microsoft·.net
江沉晚呤时5 小时前
使用 Hangfire 在 .NET 9 中实现可靠定时任务
.net
驼影随行8 小时前
ASP.NET Core 配置读取实战:IConfiguration、IOptionsSnapshot与IOptionsMonitor全解析
.net
波波00710 小时前
每日一题:请解释 .NET 中的“委托”和事件
.net