是否有一种方法可以基于我在运行时知道类的名称这一事实来创建类的实例。基本上,我将类名放在字符串中。
当前回答
也许我的问题应该更具体些。我实际上知道一个基类的字符串,所以解决它:
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
激活。CreateInstance类有各种方法以不同的方式实现相同的功能。我可以将它转换为一个对象,但上面的方法对我的情况最有用。
其他回答
看看激活器。CreateInstance除外的方法。
我曾经成功地使用过这个方法:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
您需要将返回的对象强制转换为所需的对象类型。
也许我的问题应该更具体些。我实际上知道一个基类的字符串,所以解决它:
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
激活。CreateInstance类有各种方法以不同的方式实现相同的功能。我可以将它转换为一个对象,但上面的方法对我的情况最有用。
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
你为什么要写这样的代码?如果你有一个'ReportClass'类可用,你可以直接实例化它,如下所示。
ReportClass report = new ReportClass();
代码ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(ReportClass));当没有必要的类可用,但想动态实例化和或或调用方法时使用。
我的意思是,当你知道程序集,但在写代码时,你没有类ReportClass可用时,它是有用的。
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.
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问