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
相关推荐
bugcome_com18 分钟前
深入理解 C# 特性(Attribute):概念、实现与实战
c#·.net
WebRuntime1 小时前
所有64位WinForm应用都是Chromium浏览器(2)
javascript·c#·.net·web
时光追逐者3 小时前
一款基于 .NET 9 构建的企业级 Web RBAC 快速开发框架
前端·c#·.net·.net core
许泽宇的技术分享5 小时前
当AI遇见UI:用.NET Blazor实现Google A2UI协议的完整之旅
人工智能·ui·.net·blazor·a2ui
许泽宇的技术分享6 小时前
当AI遇见UI:A2UI协议在.NET Blazor中的完整实现与深度剖析
人工智能·ui·.net·a2ui
唐青枫6 小时前
深入理解 C#.NET IEnumerable<T>:一切集合的起点
c#·.net
步步为营DotNet1 天前
深度探索.NET 中 IAsyncEnumerable:异步迭代的底层奥秘与高效实践
java·jvm·.net
时光追逐者1 天前
ASP.NET Core 依赖注入的三种服务生命周期
后端·c#·asp.net·.net·.netcore
一个帅气昵称啊2 天前
.Net如何优雅的实现发送邮件服务
.net·mail·邮件
时光追逐者2 天前
一个 WPF 开源、免费的 SVG 图像查看控件
开源·c#·.net·wpf