循环中的C#变量公式

时间:2014-07-26 14:04:57

标签: c# loops variables formula

我想在循环之前通过复选框选择我的配方。因为如果我在循环中选择配方,代码工作非常慢。所以我应该使配方变量。以下是示例代码。我怎么能这样做?

            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
        }

2 个答案:

答案 0 :(得分:3)

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

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;
}

答案 1 :(得分:0)

您可以使用表达式树使用预编译的lambda表达式来加快速度

代码段:

表达式&GT; formula1 =(x,y,z)=&gt; 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;

    }