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 - 表示程序中的两个数字,结果是执行的 > 操作的答案

我正在考虑使用一个字符或其他类似的参数来减少我在程序中其他地方使用的所有运算符

但我无法将 +、* 替换为两个整数之间的字符。:(

你们能帮忙,哪个 inbult 函数或参数可以将我的所有运算符替换为单个变量,以便我可以将它作为我的参数传递。

感谢您回答我的问题:)

4

2 回答 2

2

这种事情可以用代表来完成。内置委托类型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;
}

然后您可以使用 lambda 调用该方法:

var addResult = MakeOperationSimplifeid((x, y) => x + y);
var multResult = MakeOperationSimplifeid((x, y) => x * y);
于 2017-06-02T16:05:05.097 回答
-1

I think you can't make that, because the compiler needs the operator to compile the program. So, as I can see, the solution could be a enum, Something Like this:

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;
}
于 2012-07-23T21:49:18.410 回答