C# 从字符串创建类的实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/223952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:52:01  来源:igfitidea点击:

Create an instance of a class from a string

c#.netinstantiationsystem.type

提问by PeteT

Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.

有没有办法根据我在运行时知道类的名称这一事实来创建类的实例。基本上我会在字符串中包含类的名称。

采纳答案by Matt Hamilton

Take a look at the Activator.CreateInstancemethod.

看看Activator.CreateInstance方法。

回答by Ray Li

I've used this method successfully:

我已经成功地使用了这个方法:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

You'll need to cast the returned object to your desired object type.

您需要将返回的对象转换为所需的对象类型。

回答by PeteT

Probably my question should have been more specific. I actually know a base class for the string so solved it by:

可能我的问题应该更具体。我实际上知道字符串的基类,因此通过以下方式解决了它:

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.

Activator.CreateInstance 类有多种方法可以以不同的方式实现相同的目标。我可以将它投射到一个对象上,但以上对我的情况最有用。

回答by Asish

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));

why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.

你为什么要写这样的代码?如果您有一个可用的类“ReportClass”,您可以直接实例化它,如下所示。

ReportClass report = new ReportClass();

The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.

ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));当您没有可用的必要类,但您想动态实例化和/或调用方法时,将使用该代码。

I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClassavailable.

我的意思是当你知道程序集但在编写代码时你没有ReportClass可用的类时它很有用。

回答by Greg Osborne

For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.

例如,如果您将各种类型的值存储在一个数据库字段中(存储为字符串),并且有另一个具有类型名称的字段(即 String、bool、int、MyClass),那么从该字段数据中,您可以想象,使用上面的代码创建一个任何类型的类,并用第一个字段中的值填充它。这当然取决于您存储的类型是否具有将字符串解析为正确类型的方法。我已经多次使用它来将用户首选项设置存储在数据库中。

回答by Denny

I know I'm late to the game... but the solution you're looking for might be the combination of the above, and using an interface to define your objects publicly accessible aspects.

我知道我迟到了......但是您正在寻找的解决方案可能是上述的组合,并使用接口来定义您的对象可公开访问的方面。

Then, if all of your classes that would be generated this way implement that interface, you can just cast as the interface type and work with the resulting object.

然后,如果以这种方式生成的所有类都实现了该接口,则可以将其转换为接口类型并使用结果对象。

回答by Sarath Avanavu

Its pretty simple. Assume that your classname is Carand the namespace is Vehicles, then pass the parameter as Vehicles.Carwhich returns object of type Car. Like this you can create any instance of any class dynamically.

它很简单。假设您的类名是Car,命名空间是Vehicles,然后传递参数 asVehicles.Car返回类型的对象Car。像这样,您可以动态创建任何类的任何实例。

public object GetInstance(string strFullyQualifiedName)
{         
     Type t = Type.GetType(strFullyQualifiedName); 
     return  Activator.CreateInstance(t);         
}

If your Fully Qualified Name(ie, Vehicles.Carin this case) is in another assembly, the Type.GetTypewill be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

如果您的完全限定名称(即,Vehicles.Car在这种情况下)在另一个程序集中,Type.GetType则将为空。在这种情况下,您可以遍历所有程序集并找到Type. 为此,您可以使用以下代码

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

Now if you want to call a parameterized constructordo the following

现在,如果要调用参数化构造函数,请执行以下操作

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

instead of

代替

Activator.CreateInstance(t);

回答by asd

To create an instance of a class from another project in the solution, you can get the assembly indicated by the name of any class (for example BaseEntity) and create a new instance:

要从解决方案中的另一个项目创建类的实例,您可以获取由任何类的名称(例如 BaseEntity)指示的程序集并创建一个新实例:

  var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");