简单实现C#代码解释器

简单实现C#代码解释器

ID:37509334

大小:44.00 KB

页数:7页

时间:2019-05-24

简单实现C#代码解释器_第1页
简单实现C#代码解释器_第2页
简单实现C#代码解释器_第3页
简单实现C#代码解释器_第4页
简单实现C#代码解释器_第5页
资源描述:

《简单实现C#代码解释器》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库

1、简单的C#代码解释器1、C#代码解释器简介能够动态执行C#代码是一件很酷的功能,比如,我们可以在控制台中输入一行C#代码,然后程序自动编译并执行这一行代码,将结果显示给我们。这差不多就是一个最简单的C#代码解释器了。动态执行C#代码又是一件很有用的功能,比如,我们可以将某些代码写在某个文件之中,由程序集在执行时进行加载,改变这些代码不用中止程序,当程序再次加载这些代码时,就自动执行的是新代码了。2、简单的C#代码解释器1.usingSystem; 2.usingSystem.Collections.Generic; 3.usingSys

2、tem.Reflection; 4.usingSystem.Globalization; 5.usingMicrosoft.CSharp; 6.usingSystem.CodeDom; 7.usingSystem.CodeDom.Compiler; 8.usingSystem.Text; 9.usingSystem.IO; 10.usingSystem.Xml; 11. 12.namespaceTest 13.{ 14.classProgram 1.{ 2.staticvoidMain(string[]args) 3.{ 4.Conso

3、le.Write(">>"); 5.Stringcmd; 6.Contextcxt=newContext(); 7.while((cmd=Console.ReadLine().Trim())!="exit") 8.{ 9.if(!String.IsNullOrEmpty(cmd)) 10.{ 11.Console.WriteLine(); 12.cxt.Invoke(cmd); 13.} 14.Console.Write(">>"); 15.} 16.} 17.} 18. 19.publicclassContext 20.{ 21.

4、publicCSharpCodeProviderCodeProvider{get;set;} 22.publicIDictionaryAssemblys{get;set;} 23. 24.publicContext() 25.{ 1.CodeProvider=newCSharpCodeProvider(newDictionary(){{"CompilerVersion","v3.5"}}); 2.Assemblys=newDictionary

5、>(); 3.Assembly[]al=AppDomain.CurrentDomain.GetAssemblies(); 4.foreach(Assemblyainal) 5.{ 6.AddAssembly(a); 7.} 8.AppDomain.CurrentDomain.AssemblyLoad+=newAssemblyLoadEventHandler(CurrentDomain_AssemblyLoad); 9.} 10. 11.privatevoidAddAssembly(Assemblya) 12.{ 13.if(a!=nul

6、l) 14.{ 15.Assemblys.Add(a.FullName,a); 16.} 17.} 18. 19.voidCurrentDomain_AssemblyLoad(objectsender,AssemblyLoadEventArgsargs) 20.{ 21.Assemblya=args.LoadedAssembly; 1.if(!Assemblys.ContainsKey(a.FullName)) 2.{ 3.AddAssembly(a); 4.} 5.} 6. 7.publicCompilerParametersCrea

7、teCompilerParameters() 8.{ 9.CompilerParameterscp=newCompilerParameters(); 10.cp.GenerateExecutable=false; 11.cp.GenerateInMemory=true; 12.if(Assemblys!=null) 13.{ 14.foreach(AssemblyainAssemblys.Values) 15.{ 16.cp.ReferencedAssemblies.Add(a.Location); 17.} 18.} 19.retur

8、ncp; 20.} 21. 22.publicvoidInvoke(Stringcmd) 23.{ 24.StringinputCmdString=cmd.Trim(); 25.if(String.IsNu

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。