C#转换的动态字符串现有的类 [英] C# Convert dynamic string to existing Class

查看:91
本文介绍了C#转换的动态字符串现有的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Windows应用程序,使用C#,我有一个报告模块,将依赖于类来填充报告。但是会有很多报道,我不希望有为每一个代码。



流量将是这样:
中的报表编辑器,该报告将被分配一个类(即应用程序),作为一个字符串。
当用户选择要运行的报告,所述代码将从SQL查询获得的数据。
的代码将采取的数据,并找出哪些类将数据放入。
那么报表将采取类和填充从类的数据报告。



下面是我的dilemna,我该如何使代码动态的,所以?记住,代码将指定的类转换成正确的类对象



例如:

  GVAR =报告; 
(gVar.ReportClass)oClass =新gVar.ReportClass; // MSDN:


解决方案

使用的 Type.GetType (具体之一过载(例如, Type.GetType(字符串) )采用一个字符串参数)来加载> 为适当的类,然后使用 Activator.CreateInstance Type.GetConstructor 上的该实例键入来实例化一个实例。



所以,像

 键入类型= Type.GetType(assemblyQualifiedName); 
对象实例= Activator.CreateInstance(类型);

请注意,您必须通过的装配合格的名称除非该类型是mscorlib程序或当前执行的程序集。



此外, Activator.CreateInstance 假定一个默认的构造函数的存在。如果没有默认构造函数,或者你需要传递一些参数构造函数,你将不得不使用的 Activator.CreateInstance 相对=nofollow>超载,让你指定构造函数的参数,或者 Type.GetConstructor 加载适当的构造函数。


Within a windows app, using C#, I have a reporting module that will be reliant upon classes to populate the reports. However there will be many reports and I do not want to have to code for each one.

The flow will be as such: Within the report editor, the report will be assigned a class (i.e. "Applications") as a string. When the user selected the report to run, the code will acquire the data from a SQL query. The code will take the data and find out which class to place the data into. Then the report will take the class and populate the report with the data from the class.

Here is my dilemna, how do I make the code dynamic so that the code will convert the assigned class into the proper Class Object?

Example in mind:

gVar = Report;
(gVar.ReportClass)oClass = new gVar.ReportClass;

解决方案

Use Type.GetType (specifically one of the overloads (e.g., Type.GetType(string)) that takes a string parameter) to load the instance of Type for the appropriate class, and then use Activator.CreateInstance or Type.GetConstructor on that instance of Type to instantiate an instance.

So, something like

Type type = Type.GetType(assemblyQualifiedName);
object instance = Activator.CreateInstance(type);

Note that you must pass the assembly qualified name unless the type is in mscorlib or the currently executing assembly.

Additionally, Activator.CreateInstance assumes the existence of a default constructor. If there is not a default constructor, or you need to pass some parameters to the constructor, you will have to use an overload of Activator.CreateInstance that lets you specify the constructor parameters, or Type.GetConstructor to load the appropriate constructor.

这篇关于C#转换的动态字符串现有的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆