使用 Type.GetType(string) 方法将字符串转换为 Type 类型,Type.GetType(string) 方法的参数是类的全限定名,全限定名包含了命名空间和类名,例如:"Namespace.ClassName"。
使用 Activator.CreateInstance(Type) 方法创建指定类型的对象,Activator.CreateInstance(Type) 方法的参数是一个 Type 类型的参数,它指定要创建的类型。
下面是一个示例代码,展示了如何将字符串转换为类名:
string className = "Namespace.ClassName"
Type type = Type.GetType(className)
object obj = Activator.CreateInstance(type)
上述代码中,className 是需要转换的字符串,Type.GetType(className) 方法将 className 转换为 Type 类型,最终使用 Activator.CreateInstance(type) 方法创建了指定类型的对象,并将其存储在 obj 变量中。
需要注意的是,Type.GetType(string) 方法需要传入的字符串必须是类的全限定名,否则无法转换为 Type 类型。此外,使用 Activator.CreateInstance(Type) 方法创建对象时,如果类型没有无参构造函数,则会抛出异常。