c# – 可以在.NET应用程序中运行python吗?
发布时间:2020-12-15 08:06:54 所属栏目:百科 来源:网络整理
导读:在.NET应用程序中,可以将文本文件或数据库中的C#代码保存为字符串并动态运行.此方法在许多情况下很有用,例如业务规则引擎或用户定义的计算引擎等. 这是一个很好的例子: using System;using System.Collections.Generic;using System.Linq;using Microsoft.C
在.NET应用程序中,可以将文本文件或数据库中的C#代码保存为字符串并动态运行.此方法在许多情况下很有用,例如业务规则引擎或用户定义的计算引擎等.
这是一个很好的例子: using System; using System.Collections.Generic; using System.Linq; using Microsoft.CSharp; using System.CodeDom.Compiler; class Program { static void Main(string[] args) { var csc = new CSharpCodeProvider(new Dictionary<string,string>() { { "CompilerVersion","v3.5" } }); var parameters = new CompilerParameters(new[] { "mscorlib.dll","System.Core.dll" },"foo.exe",true); parameters.GenerateExecutable = true; CompilerResults results = csc.CompileAssemblyFromSource(parameters,@"using System.Linq; class Program { public static void Main(string[] args) { var q = from i in Enumerable.Range(1,100) where i % 2 == 0 select i; } }"); results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText)); } } 这里最重要的类是CSharpCodeProvider,它利用编译器动态编译代码. 如您所知,Python是一种广泛使用的通用高级编程语言.它的设计理念强调代码可读性,但C#很难实现.所以最好用python代替动态代码片段C#. 如何在C#应用程序中动态执行python? class Program { static void Main(string[] args) { var pythonCode = @" a=1 b=2 c=a+b return c"; //how to execute python code in c# .net } } 解决方法
IronPython是.NET(C#)中Python编程语言的一种实现.在.NET 4.0之后,可以借助DLR(动态语言运行时)将IronPython的代码嵌入到.NET应用程序中.
这是一个非常合理的最新嵌入式示例:http://www.codeproject.com/Articles/602112/Scripting-NET-Applications-with-IronPython. 您还可以阅读MSDN For Dynamic Language Runtime及其Wikipedia以获取有关该主题的其他信息. 谷歌在“How to embed IronPython in .NET”也有很多教程. 希望这可以帮助! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |