从C#中的字符串创建匿名方法 [英] Create anonymous method from a string in c#

查看:148
本文介绍了从C#中的字符串创建匿名方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从字符串中使用c#创建匿名方法?

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

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

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?

推荐答案

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

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

以下是创建(x,y,z )=> x + y * z 使用表达式树:

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

这篇关于从C#中的字符串创建匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆