要得到一个字符串中的.NET Type对象的最佳方式要得、字符串、对象、方式

2023-09-03 03:47:13 作者:安稳々

什么是一个字符串转换成.NET Type对象?

最好的方法

要考虑的问题:

的类型可以是在一个不同的组件。 类型的组件可能不会加载呢。

这是我的尝试,但它并没有解决的第二个问题

 公共功能FindType(BYVAL名作为字符串)作为类​​型
    昏暗的基地型

    基地= Reflection.Assembly.GetEntryAssembly.GetType(姓名,假,真)
    如果基地状态并没有任何然后返回基地

    基地= Reflection.Assembly.GetExecutingAssembly.GetType(姓名,假,真)
    如果基地状态并没有任何然后返回基地

    对于每一个组件,Reflection.Assembly在_
      AppDomain.CurrentDomain.GetAssemblies
        基地= assembly.GetType(姓名,假,真)
        如果基地状态并没有任何然后返回基地
    下一个
    返回任何结果
端功能
 

解决方案 excel如何提取一个字符串中的一段字符

您可能需要调用GetReferencedAssemblies()方法的第二个。

 命名空间reflectme
{
    使用系统;
    公共类打招呼
    {
        公共你好()
        {
            Console.WriteLine(你好);
            到Console.ReadLine();
        }
        静态无效的主要(字串[] args)
        {
            类型t = System.Reflection.Assembly.GetExecutingAssembly()的GetType(reflectme​​.hello)。
            t.GetConstructor(System.Type.EmptyTypes).Invoke(空);
        }
    }
}
 

What is the best way to convert a string into a Type object in .NET?

Issues to consider:

The type may be in a different assembly. The type's assembly may not be loaded yet.

This is my attempt, but it doesn't address the second issue

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

解决方案

you might need to call GetReferencedAssemblies() method for the second.

namespace reflectme
{
    using System;
    public class hello
    {
        public hello()
        {
            Console.WriteLine("hello");
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello");
            t.GetConstructor(System.Type.EmptyTypes).Invoke(null);
        }
    }
}