将字符串Lambda表达式转换为方法

时间:2017-01-16 22:02:51

标签: c# lambda

编辑:基本上我需要从用comboBox函数绘制的Draw()中选择的函数(x / 2,..)。 我需要编写一个绘制函数图的代码。我有一位代表:

delegate float Function(float x);

我的绘图功能:

void Draw(Function f)
{
    Graphics g = CreateGraphics();
    for (float i = -100; i < 100; i+=0.1f) 
    {
        g.DrawString(".", new Font("arial", 10), Brushes.Black, i+200, ClientSize.Height-(f(i) + 100));
    }
}

在MainFormLoad上我加载了我的数组(这可能不是这样做的正确方法,但我有点迷失了怎么办)。 arr包含我想要绘制的函数。

void MainFormLoad(object sender, EventArgs e)
{
    string[] arr;
    arr = new string[] {"x / 2", "50 * Math.Sin(x / 50.0)"};
    var arr = from item in arr select item;
    foreach (var i in arr)
    {
        comboBox1.Items.Add(i);
    }
}

然后在ButtonClick上我尝试调用它:

void Button1Click(object sender, EventArgs e)
{
    //Draw(x => x / 2) It should work this way
    Draw(x => (Combobox1. something here ?));
}

3 个答案:

答案 0 :(得分:0)

我知道你评论过你不想要外部库,但是当我读到这篇文章时我刚刚完成了答案。所以,就是这样。您可以使用Ncalc,它非常易于使用,请查看

class Program
{
    static void Main(string[] args)
    {
        var strFunc = "10000/x";
        for (var i = 1; i < 10000; i++)
        {
            var strFuncRplacement = strFunc.Replace("x", i.ToString());
            var e = new Expression(strFuncRplacement);
            Console.WriteLine(e.Evaluate());
        }
        Console.ReadLine();
    }
}

您只需安装nuget包和using指令

即可
using NCalc;

通过这种方式,您可以节省大量精力和代码行

希望它可以帮到你

答案 1 :(得分:0)

我不确定我是否正确理解了这个问题,但我认为你可以这样做:

而不是

void Draw(Function f)

使用

void Draw(Func<double, double> f)

而不是

arr = new string[] {"x / 2", "50 * Math.Sin(x / 50.0)"};

使用

var arr = new Func<double, double>[] {(double x) => x/2, (double x) => Math.Sin(x)};

答案 2 :(得分:0)

有什么理由将函数声明为字符串类型而不是函数类型?

如果不是,则将数组arr更改为Function数组并使用Functions启动它。

如果是,则无法进行,因为您无法仅使用c#中的标准库将字符串转换为c#代码。

相关问题