Jon*_*len 7 .net reflection system.reflection
在.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
Run Code Online (Sandbox Code Playgroud)
Jar*_*Par 10
您可以使用Type.GetType(string)来执行此操作.类型名称必须是程序集限定的,但该方法将根据需要加载程序集.如果类型位于mscorlid或执行GetType调用的程序集中,则不需要程序集限定.
您可能需要为第二个调用 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)