C#动态创建类
程序员文章站
2023-12-28 11:56:40
...
C#动态创建类
public static void CreatNewClass(int i, int j)
{
StringBuilder sbCode = new StringBuilder();
sbCode.AppendLine("using System;");
sbCode.AppendLine("namespace Entity");
sbCode.AppendLine("{");
sbCode.AppendLine(" public class Test");
sbCode.AppendLine(" {");
sbCode.AppendLine(" public int i;");
sbCode.AppendLine(" public int j;");
sbCode.AppendLine(" }");
sbCode.AppendLine("}");
// 编译器
CodeDomProvider cdp = CodeDomProvider.CreateProvider("C#");
// 编译器的参数
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
CompilerResults cr = cdp.CompileAssemblyFromSource(cp, sbCode.ToString());
if (!cr.Errors.HasErrors)
{
//反射实例化数据库字段
Assembly ass = cr.CompiledAssembly;
object DataInfoEntity = ass.CreateInstance("Entity.Test");
//获取test类
Type type = ass.GetType("Entity.Test");
//赋值
FieldInfo infoI = type.GetField("i");
infoI.SetValue(DataInfoEntity, i);
FieldInfo infoJ = type.GetField("j");
infoJ.SetValue(DataInfoEntity, j);
//获取值
int intI = (int)infoI.GetValue(DataInfoEntity);
int intJ = (int)infoJ.GetValue(DataInfoEntity);
Console.WriteLine("j+i结果:" + (intI + intJ));
}
else
{
Console.WriteLine("编译失败");
}
}
调用
static void Main()
{
CreatNewClass(8,8);
}