循环中的c#变量公式

本文关键字:变量 循环 | 更新日期: 2023-09-27 18:14:52

我想在循环前通过复选框选择公式。因为如果我在循环中选择公式,代码就会运行得很慢。所以我应该把公式变成变量。下面是一个示例代码。我该怎么做呢?

            formula1 = 2 * a + b;
            formula2 = 4 * a + 2 * c;
            formula3= 2 * c + 12 * b + a;
            if (checkBox1.Checked==true)
            {formula_select=formula1}
            if (checkBox2.Checked==true)
            {formula_select=formula2}
            if (checkBox3.Checked==true)
            {formula_select=formula3}
            for (int i = 1; i < 500000; i++)
        {
                a=a+1;
                b=5
                c=2;
                formula_select   //for example; formula 2 should be calculated here
                formula_select* some_numbers; // answer of formula2 should be used here
                other calculations
        }

循环中的c#变量公式

要选择要执行的公式,可以使用委托。例子:

Func<int, int, int, int> formula_select;
if (checkBox1.Checked) {
  formula_select = (a, b, c) => 2 * a + b;
} else if (checkBox2.Checked) {
  formula_select = (a, b, c) => 4 * a + 2 * c;
} else if (checkBox3.Checked) {
  formula_select = (a, b, c) => 2 * c + 12 * b + a;
}
for (int i = 1; i < 500000; i++) {
  a=a+1;
  b=5
  c=2;
  int x = formula_select(a, b, c);
  int y = x * some_numbers;
}

然而,由于在函数调用中有一些开销,它可能不会使它更快。它不确定实际上是代码的那一部分很慢。您应该尝试简单地将复选框控件中的状态存储在变量中并在循环中使用,这可能是实际的瓶颈所在:

bool check1 = checkBox1.Checked;
bool check2 = checkBox2.Checked;
bool check3 = checkBox3.Checked;
for (int i = 1; i < 500000; i++) {
  a=a+1;
  b=5
  c=2;
  int x;
  if (check1) {
    x = 2 * a + b;
  } else if (check2) {
    x = 4 * a + 2 * c;
  } else if (check3) {
    x = 2 * c + 12 * b + a;
  }
  int y = x * some_numbers;
}

您可以使用使用表达式树的预编译lambda表达式使其更快

代码片段:

表达式>的民用= (x, y, z) => 2 * x + y;

        Expression<Func<int, int, int, int>> formula2 = (x, y, z) => 4 * x + 2 * z;
        Expression<Func<int, int, int, int>> formula3 = (x, y, z) => 2 * z + 12 * y + x;

        Func<int, int, int, int> formula_select=null;
         if (this.formula1.IsChecked.HasValue &&this.formula1.IsChecked.Value)
        {
            formula_select = formula1.Compile(); 
        }
        else if (this.formula2.IsChecked.HasValue&&this.formula2.IsChecked.Value)
        {
            formula_select = formula2.Compile();
        }
        else if (this.formula3.IsChecked.HasValue&&this.formula3.IsChecked.Value)
        {
            formula_select = formula3.Compile(); 
        }
        int a=0, b, c,someNumber=1;
        for (int i = 1; i < 500000; i++)
    {
            a=a+1;
            b=5;
            c=2;
            int result=formula_select(a,b,c);
            int someResult = result * someNumber;
    }