2012-07-23 25 views
1
public int MainOperationSimplifeid(char operatoru) 
    { 
     if (beforeoperation == 2) 
     { 
      a2 = Convert.ToInt32(textBox1.Text); 
      textBox1.Text = ""; 
      result = a1 operatoru a2; 
      // textBox1.Text = Convert.ToString(result); 
      a1 = 0; 
      a2 = 0; 
     } 
     beforeoperation++; 
     return result; 
    } 

A1做一个计算器,A2 - 代表在节目中两个数字,结果是答案的>操作peformed我如何可以通过运营商作为参数传递给一个函数,我在C#

我想到使用其他地方使用的程序

一个单个字符或减少我的所有运营商的一些其他类似的说法,但我不能得到+,*两个整数之间更换为char。 :(

你们可以请帮助这inbult功能或参数可以代替我所有的运营商一个变量,这样我可以传递我的论点。

感谢您在我的问题去:)

回答

-1

我认为你不能这样做,因为编译器需要操作员编译程序。所以,我可以看到,该解决方案可能是一个enum,事情是这样的:

Enum Operator { 
    Addition, Substraction, Multiplication, Division 
}; 

public double MainOperationSimplified(Operator operatoru) 
{ 
    if (beforeoperation == 2) 
    { 
     a2 = Convert.ToInt32(textBox1.Text); 
     textBox1.Text = ""; 

     switch (operatoru) { 
      case Addition: 
       result = a1 + a2; 
       break; 
      case Substraction: 
       result = a1 - a2; 
       break; 
      case Multiplication: 
       result = a1 * a2; 
       break; 
      case Division: 
       result = a1/a2; 
       break; 
      default: 
       result = 0; 
       break; 
     } 

     a1 = 0; 
     a2 = 0; 
    } 
    beforeoperation++; 
    return result; 
} 
+0

感谢的答案,还是我期待一点点简单的答案或意味着更加直接的答案。切换4的情况下看起来不错,但我正在考虑一个更大的运营商堆栈,提供我自己的运营商更好的功能 – 2012-07-24 09:10:08

1

这样的事情可以委托来完成。内置委托类型Func<T1, T2, T3>表示接受两个参数并返回结果的代码。

public int MainOperationSimplifeid(Func<int, int, int> operatoru) 
{ 
    if (beforeoperation == 2) 
    { 
     a2 = Convert.ToInt32(textBox1.Text); 
     textBox1.Text = ""; 
     result = operatoru(a1, a2); 
     // textBox1.Text = Convert.ToString(result); 
     a1 = 0; 
     a2 = 0; 
    } 
    beforeoperation++; 
    return result; 
} 

然后就可以调用该方法以拉姆达:

var addResult = MakeOperationSimplifeid((x, y) => x + y); 
var multResult = MakeOperationSimplifeid((x, y) => x * y); 
相关问题