English 中文(简体)
引证[复制]
原标题:Creating lambda expression from a string [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Is there an easy way to parse a (lambda expression) string into an Action delegate?

我愿将“拉姆布达”的表述储存在一个集邮档案中,并且以动态方式将这些示意图装入“C#”中的“玛目”。 我的目标是混淆和注入规则。 是否有任何公用事业可用以从护法中产生lam语吗?

是否有其他轻重解决办法实现同样的目标?

问题回答

如果你事先知道这些表述的类型,那么你可以将其汇编成一类,然后从由此产生的大会中撤回。

这里有一个例子,它的确(用言词来扼杀和归还ool)并且管理由此产生的规则。

c. 系。 ::

file => file.Length == 0
file => System.IO.Path.GetExtension(file) == ".txt"
file => file == null

由此得出的产出是:

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:	emp
ules.txt: False
Checking rule file => (GetExtension(file) == ".txt") against input c:	emp
ules.txt: True
Checking rule file => (file == null) against input c:	emp
ules.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:	emp
ules.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: 
{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;
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签