我想创建一个在函数中传递名称的类.我怎么做?
基本上我的意思是:我们有一个叫做的函数
public void CreateClassWithThisName(string name)
{
}
Run Code Online (Sandbox Code Playgroud)
然后我们创建一个类
class name
{
//this name is the one passed as parameter in function CreateClassWithThisName
private Id {get;set}
}
Run Code Online (Sandbox Code Playgroud)
我假设您的意思是要创建具有给定名称的类的实例.您可以使用:
Type type = Type.GetType(name);
object instance = Activator.CreateInstance(type);
Run Code Online (Sandbox Code Playgroud)
但请注意:
name 必须是完全限定的类型名称,包括名称空间name必须是程序集限定的类型名称Activator.CreateInstance来指定构造函数参数您还可以使用Assembly.GetType(string)从特定程序集中获取类型.