从 C# 中的字符串创建匿名方法

发布于 2024-08-08 03:05:15 字数 155 浏览 6 评论 0原文

是否可以在 C# 中从字符串创建匿名方法?

例如,如果我有一个字符串 "x + y * z" 是否可以将其转换为某种方法/lambda 对象,我可以使用任意 x,< code>y,z 参数?

is it possible to create an anonymous method in c# from a string?

e.g. if I have a string "x + y * z" is it possible to turn this into some sort of method/lambda object that I can call with arbitrary x,y,z parameters?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

双马尾 2024-08-15 03:05:15

这是可能的,是的。您必须解析字符串,例如使用表达式树编译委托。

这是创建 (x, y, z) => 的示例x + y * z 使用表达式树:

ParameterExpression parameterX = Expression.Parameter(typeof(int), "x");
ParameterExpression parameterY = Expression.Parameter(typeof(int), "y");
ParameterExpression parameterZ = Expression.Parameter(typeof(int), "z");
Expression multiplyYZ = Expression.Multiply(parameterY, parameterZ);
Expression addXMultiplyYZ = Expression.Add(parameterX, multiplyYZ);
Func<int,int,int,int> f = Expression.Lambda<Func<int, int, int, int>>
(
    addXMultiplyYZ,
    parameterX,
    parameterY,
    parameterZ
).Compile();
Console.WriteLine(f(24, 6, 3)); // prints 42 to the console

It's possible, yes. You have to parse the string and, for example, compile a delegate using expression trees.

Here's an example of creating (x, y, z) => x + y * z using expression trees:

ParameterExpression parameterX = Expression.Parameter(typeof(int), "x");
ParameterExpression parameterY = Expression.Parameter(typeof(int), "y");
ParameterExpression parameterZ = Expression.Parameter(typeof(int), "z");
Expression multiplyYZ = Expression.Multiply(parameterY, parameterZ);
Expression addXMultiplyYZ = Expression.Add(parameterX, multiplyYZ);
Func<int,int,int,int> f = Expression.Lambda<Func<int, int, int, int>>
(
    addXMultiplyYZ,
    parameterX,
    parameterY,
    parameterZ
).Compile();
Console.WriteLine(f(24, 6, 3)); // prints 42 to the console
橘寄 2024-08-15 03:05:15

只是为了使用 CodeDom 的乐趣(字符串中允许任何有效的 C# 代码,只要它存在于 mscorlib 中即可(根本不检查错误):

static class Program
{
    static string code = @"
        public static class __CompiledExpr__
        {{
            public static {0} Run({1})
            {{
                return {2};
            }}
        }}
        ";

    static MethodInfo ToMethod(string expr, Type[] argTypes, string[] argNames, Type resultType)
    {
        StringBuilder argString = new StringBuilder();
        for (int i = 0; i < argTypes.Length; i++)
        {
            if (i != 0) argString.Append(", ");
            argString.AppendFormat("{0} {1}", argTypes[i].FullName, argNames[i]);
        }
        string finalCode = string.Format(code, resultType != null ? resultType.FullName : "void",
            argString, expr);

        var parameters = new CompilerParameters();
        parameters.ReferencedAssemblies.Add("mscorlib.dll");
        parameters.ReferencedAssemblies.Add(Path.GetFileName(Assembly.GetExecutingAssembly().Location));
        parameters.GenerateInMemory = true;

        var c = new CSharpCodeProvider();
        CompilerResults results = c.CompileAssemblyFromSource(parameters, finalCode);
        var asm = results.CompiledAssembly;
        var compiledType = asm.GetType("__CompiledExpr__");
        return compiledType.GetMethod("Run");
    }

    static Action ToAction(this string expr)
    {
        var method = ToMethod(expr, new Type[0], new string[0], null);
        return () => method.Invoke(null, new object[0]);
    }

    static Func<TResult> ToFunc<TResult>(this string expr)
    {
        var method = ToMethod(expr, new Type[0], new string[0], typeof(TResult));
        return () => (TResult)method.Invoke(null, new object[0]);
    }

    static Func<T, TResult> ToFunc<T, TResult>(this string expr, string arg1Name)
    {
        var method = ToMethod(expr, new Type[] { typeof(T) }, new string[] { arg1Name }, typeof(TResult));
        return (T arg1) => (TResult)method.Invoke(null, new object[] { arg1 });
    }

    static Func<T1, T2, TResult> ToFunc<T1, T2, TResult>(this string expr, string arg1Name, string arg2Name)
    {
        var method = ToMethod(expr, new Type[] { typeof(T1), typeof(T2) },
            new string[] { arg1Name, arg2Name }, typeof(TResult));
        return (T1 arg1, T2 arg2) => (TResult)method.Invoke(null, new object[] { arg1, arg2 });
    }

    static Func<T1, T2, T3, TResult> ToFunc<T1, T2, T3, TResult>(this string expr, string arg1Name, string arg2Name, string arg3Name)
    {
        var method = ToMethod(expr, new Type[] { typeof(T1), typeof(T2), typeof(T3) },
            new string[] { arg1Name, arg2Name, arg3Name }, typeof(TResult));
        return (T1 arg1, T2 arg2, T3 arg3) => (TResult)method.Invoke(null, new object[] { arg1, arg2, arg3 });
    }

    static void Main(string[] args)
    {
        var f = "x + y * z".ToFunc<int, int, long, long>("x", "y", "z");
        var x = f(3, 6, 8);

    }
}

Just for fun using CodeDom (any valid C# code is allowed in the string as long as it is present in mscorlib (No check for errors at all):

static class Program
{
    static string code = @"
        public static class __CompiledExpr__
        {{
            public static {0} Run({1})
            {{
                return {2};
            }}
        }}
        ";

    static MethodInfo ToMethod(string expr, Type[] argTypes, string[] argNames, Type resultType)
    {
        StringBuilder argString = new StringBuilder();
        for (int i = 0; i < argTypes.Length; i++)
        {
            if (i != 0) argString.Append(", ");
            argString.AppendFormat("{0} {1}", argTypes[i].FullName, argNames[i]);
        }
        string finalCode = string.Format(code, resultType != null ? resultType.FullName : "void",
            argString, expr);

        var parameters = new CompilerParameters();
        parameters.ReferencedAssemblies.Add("mscorlib.dll");
        parameters.ReferencedAssemblies.Add(Path.GetFileName(Assembly.GetExecutingAssembly().Location));
        parameters.GenerateInMemory = true;

        var c = new CSharpCodeProvider();
        CompilerResults results = c.CompileAssemblyFromSource(parameters, finalCode);
        var asm = results.CompiledAssembly;
        var compiledType = asm.GetType("__CompiledExpr__");
        return compiledType.GetMethod("Run");
    }

    static Action ToAction(this string expr)
    {
        var method = ToMethod(expr, new Type[0], new string[0], null);
        return () => method.Invoke(null, new object[0]);
    }

    static Func<TResult> ToFunc<TResult>(this string expr)
    {
        var method = ToMethod(expr, new Type[0], new string[0], typeof(TResult));
        return () => (TResult)method.Invoke(null, new object[0]);
    }

    static Func<T, TResult> ToFunc<T, TResult>(this string expr, string arg1Name)
    {
        var method = ToMethod(expr, new Type[] { typeof(T) }, new string[] { arg1Name }, typeof(TResult));
        return (T arg1) => (TResult)method.Invoke(null, new object[] { arg1 });
    }

    static Func<T1, T2, TResult> ToFunc<T1, T2, TResult>(this string expr, string arg1Name, string arg2Name)
    {
        var method = ToMethod(expr, new Type[] { typeof(T1), typeof(T2) },
            new string[] { arg1Name, arg2Name }, typeof(TResult));
        return (T1 arg1, T2 arg2) => (TResult)method.Invoke(null, new object[] { arg1, arg2 });
    }

    static Func<T1, T2, T3, TResult> ToFunc<T1, T2, T3, TResult>(this string expr, string arg1Name, string arg2Name, string arg3Name)
    {
        var method = ToMethod(expr, new Type[] { typeof(T1), typeof(T2), typeof(T3) },
            new string[] { arg1Name, arg2Name, arg3Name }, typeof(TResult));
        return (T1 arg1, T2 arg2, T3 arg3) => (TResult)method.Invoke(null, new object[] { arg1, arg2, arg3 });
    }

    static void Main(string[] args)
    {
        var f = "x + y * z".ToFunc<int, int, long, long>("x", "y", "z");
        var x = f(3, 6, 8);

    }
}
星星的軌跡 2024-08-15 03:05:15

C# 没有任何这样的功能(其他语言 - 比如 JavaScript - 有 eval 函数来处理这样的东西)。您需要解析该字符串并使用表达式树或通过发出 IL 自行创建一个方法。

C# doesn't have any functionality like this (other languages - like JavaScript - have eval functions to handle stuff like this). You will need to parse the string and create a method yourself with either expression trees or by emitting IL.

呢古 2024-08-15 03:05:15

.Net 框架中有执行此操作的功能。

这并不容易。您需要在该语句周围添加一些代码,以使其成为一个完整的程序集,包括您可以调用的类和方法。

之后,将字符串传递给

CSharpCodeProvider.CompileAssemblyFromSource(options, yourcode);

Here is an example

There are functionality to do this in the .Net framework.

It is not easy. You need to add some code around the statement to make it into a complete assembly including a class and method you can call.

After that you pass the string to

CSharpCodeProvider.CompileAssemblyFromSource(options, yourcode);

Here is an example

空名 2024-08-15 03:05:15

使用语法(例如 ANTLR)和创建表达式树的解释器是可能的。这不是一个小任务,但是,如果您限制接受输入的范围,您就可以成功。以下是一些参考资料:

以下是一些代码可能会转换的内容将 ANTLR ITree 转换为表达式树。它并不完整,但向您展示了您面临的挑战。

private Dictionary<string, ParameterExpression> variables
    = new Dictionary<string, ParameterExpression>();

public Expression Visit(ITree tree)
{
    switch(tree.Type)
    {
        case MyParser.NUMBER_LITERAL:
            {
                float value;
                var literal = tree.GetChild(0).Text;
                if (!Single.TryParse(literal, out value))
                    throw new MyParserException("Invalid number literal");
                return Expression.Constant(value);
            }

        case MyParser.IDENTIFIER:
            {
                var ident = tree.GetChild(0).Text;
                if (!this.variables.ContainsKey(ident))
                {
                    this.variables.Add(ident,
                       Expression.Parameter(typeof(float), ident));
                }

                return this.variables[ident];
            }

        case MyParser.ADD_EXPR:
            return Expression.Add(Visit(tree.GetChild(0)), Visit(tree.GetChild(1)));

        // ... more here
    }
}

It could be possible with a grammar (e.g. ANTLR) and an interpreter which creates expression trees. This is no small task, however, you can be successful if you limit the scope of what you accept as input. Here are some references:

Here is what some code may look like to transform an ANTLR ITree into an Expression tree. It isn't complete, but shows you what you're up against.

private Dictionary<string, ParameterExpression> variables
    = new Dictionary<string, ParameterExpression>();

public Expression Visit(ITree tree)
{
    switch(tree.Type)
    {
        case MyParser.NUMBER_LITERAL:
            {
                float value;
                var literal = tree.GetChild(0).Text;
                if (!Single.TryParse(literal, out value))
                    throw new MyParserException("Invalid number literal");
                return Expression.Constant(value);
            }

        case MyParser.IDENTIFIER:
            {
                var ident = tree.GetChild(0).Text;
                if (!this.variables.ContainsKey(ident))
                {
                    this.variables.Add(ident,
                       Expression.Parameter(typeof(float), ident));
                }

                return this.variables[ident];
            }

        case MyParser.ADD_EXPR:
            return Expression.Add(Visit(tree.GetChild(0)), Visit(tree.GetChild(1)));

        // ... more here
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文