临近下班,一同事突然问到:“如何用DotNet动态生成代码的类?”噫,静态语言要实现动态生成类,有点意思,不过这又有什么实际的应用呢?随手查了一下.Net Framework中提供的类库,看到Microsoft.Csharp命名空间,其Compiler类已经实现了编译器的托管包装。这下方便了,先实现代码看一下:
using System;
using System.IO;
using System.Text;
using Microsoft.CSharp;
namespace TestProject
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
public class DynamicCompile
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
private String _physicspath = @"D:\Project.Net\TestProject\DcCodeFile\";//文件夹的路径
private String _outputpath = @"D:\Project.Net\TestProject\bin";//输出文件的路径
private String[] _filelist; //文件列表
private String[] _cscode; //源码
private String[] _filename; //文件名
private String[] _import; //引用
private System.Collections.IDictionary configs = null;//编译属性参数配置
public DynamicCompile()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{}
public CompilerError[] ExCompiler()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Fill_cscode();
Fill_import();
Fill_configs();
CompilerError[] ce= Compiler.Compile(_cscode,_filename, _outputpath,_import, configs);
return ce;
}
private String[] Fill_filelist()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return System.IO.Directory.GetFiles(_physicspath,"*.cs");
}
private void Fill_cscode()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
_filelist= Fill_filelist();
_cscode=new String[_filelist.Length];
_filename=new String[_filelist.Length];
for(int i=0;i<_filelist.Length;i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
String filepath= _filelist.GetValue(i).ToString();//获取文件路径
_cscode[i]= ReadCodeFile(filepath, Encoding.GetEncoding("utf-8"));
_filename[i]= System.IO.Path.GetFileName(filepath);
}
}
private void Fill_import()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
_import=new String[10];//数组长度视引用文件数量
_import[0]=@"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll";
_import[1]=@"C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Web.dll";
}
private void Fill_configs()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
configs=new System.Collections.Specialized.ListDictionary();
configs.Add("target","library");
}
//读取cscode内容
private String ReadCodeFile(String path,Encoding encode)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
String content=String.Empty;
try
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (File.Exists(path))
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
StreamReader sr=new StreamReader(path,encode);
content=sr.ReadToEnd();
sr.Close();
}
}
catch(IOException ex)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.Write(ex.ToString());
}
return content;
}
}
}
个人感觉如果只是为了加强系统的灵活性而动态生成代码类,并无太大意义,不知哪位有经验的兄弟来说两句。