gpt4 book ai didi

.net - 从 .NET 中的字符串获取 Type 对象的最佳方法

转载 作者:行者123 更新时间:2023-12-04 10:33:07 24 4
gpt4 key购买 nike

在 .NET 中将字符串转换为 Type 对象的最佳方法是什么?

需要考虑的问题:

  • 类型可能在不同的程序集中。
  • 类型的程序集可能尚未加载。

  • 这是我的尝试,但它没有解决第二个问题
    Public Function FindType(ByVal name As String) As Type
    Dim base As Type

    base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True)
    If base IsNot Nothing Then Return base

    base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True)
    If base IsNot Nothing Then Return base

    For Each assembly As Reflection.Assembly In _
    AppDomain.CurrentDomain.GetAssemblies
    base = assembly.GetType(name, False, True)
    If base IsNot Nothing Then Return base
    Next
    Return Nothing
    End Function

    最佳答案

    您可以使用 Type.GetType(string)为此。类型名称必须是程序集限定的,但该方法将根据需要加载程序集。如果类型在 mscorlid 或执行 GetType 调用的程序集中,则不需要程序集限定。

    关于.net - 从 .NET 中的字符串获取 Type 对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/608332/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com