从 .NET 中的字符串获取 Type 对象的最佳方法
-
03-07-2019 - |
题
在 .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
解决方案
您可能需要为第二个调用 GetReferencedAssemblies() 方法。
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);
}
}
}
其他提示
您可以使用 类型.GetType(字符串) 为此。类型名称必须是程序集限定的,但该方法将根据需要加载程序集。如果类型位于 mscorlid 或执行 GetType 调用的程序集中,则不需要程序集限定。
不隶属于 StackOverflow