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
相关推荐
界面开发小八哥4 小时前
界面控件DevExpress WinForms中文帮助文档 - 入门指南
ai·c#·.net·devexpress·ui开发·winforms
清风与日月5 小时前
Yitter.IdGenerator:高性能分布式唯一ID生成器详解
分布式·c#·.net·.netcore
大鹏说大话8 小时前
用 Semantic Kernel 在 .NET 中构建你的第一个 AI 智能体(Agent)
人工智能·.net
七仔啊9 小时前
C#、.NET 、ASP.NET Core、Visual Studio全系列快速入门
c#·asp.net·.net
超龄超能程序猿9 小时前
实战优化:.NET 8 容器 Debian 源+时间同步企业级 Dockerfile
运维·debian·.net
一个帅气昵称啊1 天前
.Net C# AI智能体开发-快速开始
开发语言·c#·.net
kyle~1 天前
.NET 软件开发平台
.net
一个帅气昵称啊1 天前
.Net C# AI智能体开发-AI智能体
人工智能·c#·.net
码农刚子2 天前
用 .NET 8 + uni-app 做一套多租户畜牧 SaaS:我们在秦巴牧云踩过的 6 个坑
uni-app·.net·saas
宝桥南山4 天前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore