从包含类定义的字符串创建动态类

时间:2018-01-02 14:07:40

标签: c# .net dynamic-class-creation

我有一个接受表名的存储过程,然后它读取表结构并以字符串形式定义表结构。

E.g:

string myString = 
 "
   public class TableName
   { 
     public int Column1 { get; set; } 
   }
 "

是否可以从包含类定义的字符串创建一个Class / Type? 例如: -

Type type = GenerateType(myString);

我必须将此类型变量传递给我的另一段代码,所以请帮我从包含类定义的字符串创建类/类型。

1 个答案:

答案 0 :(得分:6)

您可以使用CSharpCodeProvider在运行时编译结果,然后使用Activator - Class从生成的代码中创建对象。

// compile your piece of code to dll file
Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
System.CodeDom.Compiler.CompilerResults cResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, "using System; namespace Tables { 'put here your class definition' }");

// then load your dll file, get type and object from class
Assembly assembly = cResult.CompiledAssembly;
Type myTableType = assembly.GetType("Tables.Tablename");
var finalResult = Activator.CreateInstance(myTableType);