从字符串创建lambda表达式 [英] Creating lambda expression from a string
问题描述
可能重复:结果
的是否有一个简单的方法来分析字符串一(lambda表达式)到Action委托?
我想lambda表达式作为字符串存储在一个配置文件并在运行时动态地加载这些字符串放到拉姆达表达式在C#。我的目标是配置和注入的规则。任何可以从一个字符串创建lambda表达式的事业吗?
I would like to store lambda expressions as strings in a config file and at runtime dynamically load these strings into lambda expressions in C#. My objective is to configure and inject rules. Any utilities available for creating lambda expressions from a string ?
是否有同样目标的任何其他重量轻的解决方案?
Are there any other light weight solutions for the same objective ?
推荐答案
如果您知道表达式的时间提前的类型,那么你可以把它们编译成类的一部分,然后从所得到的组件将他们拉回来。
If you know the type of the expressions ahead of time, then you can compile them as part of a class then pull them back out from the resulting assembly.
下面是一条什么(用表达式以一个字符串,并返回一个布尔)的和运行所产生的规则的例子。
Here's an example that does (with the expressions taking a string and returning a bool) that and runs the resulting rules.
通过C的内容:\temp\rules.txt此为:
With the contents of c:\temp\rules.txt being this:
file => file.Length == 0
file => System.IO.Path.GetExtension(file) == ".txt"
file => file == null
然后输出结果是这样的:
Then the resulting output is this:
Rules found in file:
file => file.Length == 0,
file => System.IO.Path.GetExtension(file) == ".txt",
file => file == null,
Checking rule file => (file.Length == 0) against input c:\temp\rules.txt: False
Checking rule file => (GetExtension(file) == ".txt") against input c:\temp\rules.txt: True
Checking rule file => (file == null) against input c:\temp\rules.txt: False
来源
using System;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Linq.Expressions;
class Program
{
private const string classTemplate = @"
using System;
using System.Linq.Expressions;
public static class RulesConfiguration
{{
private static Expression<Func<string, bool>>[] rules = new Expression<Func<string, bool>>[]
{{
{0}
}};
public static Expression<Func<string, bool>>[] Rules {{ get {{ return rules; }} }}
}}
";
static void Main(string[] args)
{
var filePath = @"c:\temp\rules.txt";
var fileContents = File.ReadAllLines(filePath);
// add commas to the expressions so they can compile as part of the array
var joined = String.Join("," + Environment.NewLine, fileContents);
Console.WriteLine("Rules found in file: \n{0}", joined);
var classSource = String.Format(classTemplate, joined);
var assembly = CompileAssembly(classSource);
var rules = GetExpressionsFromAssembly(assembly);
foreach (var rule in rules)
{
var compiledToFunc = rule.Compile();
Console.WriteLine("Checking rule {0} against input {1}: {2}", rule, filePath, compiledToFunc(filePath));
}
}
static Expression<Func<string, bool>>[] GetExpressionsFromAssembly(Assembly assembly)
{
var type = assembly.GetTypes().Single();
var property = type.GetProperties().Single();
var propertyValue = property.GetValue(null, null);
return propertyValue as Expression<Func<string, bool>>[];
}
static Assembly CompileAssembly(string source)
{
var compilerParameters = new CompilerParameters()
{
GenerateExecutable = false,
GenerateInMemory = true,
ReferencedAssemblies =
{
"System.Core.dll" // needed for linq + expressions to compile
},
};
var compileProvider = new CSharpCodeProvider();
var results = compileProvider.CompileAssemblyFromSource(compilerParameters, source);
if (results.Errors.HasErrors)
{
Console.Error.WriteLine("{0} errors during compilation of rules", results.Errors.Count);
foreach (CompilerError error in results.Errors)
{
Console.Error.WriteLine(error.ErrorText);
}
throw new InvalidOperationException("Broken rules configuration, please fix");
}
var assembly = results.CompiledAssembly;
return assembly;
}
}
这篇关于从字符串创建lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!