110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Collections;
using Microsoft.CSharp;
namespace Reporter.Windows
{
class ReporterCodeDom
{
public Assembly NewAssembly(ArrayList arraylist)
{
//创建编译器实例。
CSharpCodeProvider provider = new CSharpCodeProvider();
//设置编译参数。
CompilerParameters paras = new CompilerParameters();
paras.ReferencedAssemblies.Add("System.dll");
paras.GenerateExecutable = false;
paras.GenerateInMemory = true;
//创建动态代码。
StringBuilder classSource = new StringBuilder();
classSource.Append("using System.Collections.Generic;\n");
classSource.Append("using System;\n");
classSource.Append("using System.Text;\n");
classSource.Append("using System.ComponentModel;");
classSource.Append("namespace Reporter.Windows\n");
classSource.Append("{\n");
classSource.Append("public class DynamicClass \n");
classSource.Append("{\n");
//创建属性。
for (int i = 1; i < arraylist.Count; i++)
{
classSource.Append(propertyString(arraylist[i].ToString()));
}
classSource.Append("\n}");
classSource.Append("\n}");
System.Diagnostics.Debug.WriteLine(classSource.ToString());
//编译代码。
CompilerResults result = provider.CompileAssemblyFromSource(paras, classSource.ToString());
//获取编译后的程序集。
Assembly assembly = result.CompiledAssembly;
return assembly;
}
public void ReflectionSetProperty(object objClass, string propertyName, string value)
{
PropertyInfo[] infos = objClass.GetType().GetProperties();
foreach (PropertyInfo info in infos)
{
if (info.Name == propertyName && info.CanWrite)
{
info.SetValue(objClass, value, null);
}
}
}
public ArrayList ReflectionGetProperty(object objClass, string propertyName)
{
PropertyInfo[] infos = objClass.GetType().GetProperties();
ArrayList arrayValue = new ArrayList();
foreach (PropertyInfo info in infos)
{
if (info.Name == propertyName && info.CanRead)
{
//System.Console.WriteLine(info.GetValue(objClass, null));
arrayValue.Add(info.GetValue(objClass, null).ToString());
}
}
return arrayValue;
}
public string propertyString(string propertyName)
{
StringBuilder sbProperty = new StringBuilder();
sbProperty.Append(" \nprivate string _" + propertyName + " = null;\n");
sbProperty.Append("[Category(\"属性配置(装置物料代码配置)\")]\n");
sbProperty.Append(" public string " + "" + propertyName + "\n");
sbProperty.Append(" {\n");
sbProperty.Append(" get{ return _" + propertyName + ";} \n");
sbProperty.Append(" set{ _" + propertyName + " = value; }\n");
sbProperty.Append(" }");
return sbProperty.ToString();
}
public ArrayList GetClass1(object C,ArrayList newArrayValue)
{
ArrayList arraylist = new ArrayList();
for (int i = 1; i < newArrayValue.Count; i++)
{
arraylist.Add(C.GetType().GetProperty(newArrayValue[i].ToString()).GetValue(C, null).ToString());
}
return arraylist;
}
}
}