Had*_*ifi 7 .net c# python ironpython dynamic
在.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));
}
}
Run Code Online (Sandbox Code Playgroud)
这里最重要的类是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
}
}
Run Code Online (Sandbox Code Playgroud)
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以获取有关该主题的其他信息.
Google还提供了有关"如何在.NET中嵌入IronPython"的教程.
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
3888 次 |
| 最近记录: |