简体   繁体   English

在 c# 中将 += 或 -= 作为参数传递

[英]Pass += or -= as a parameter in c#

I have a method from a button click with the following code in c# (small golf scoring program I'm working on just for fun):我有一个按钮单击方法,在 c# 中使用以下代码(我正在开发的小型高尔夫评分程序只是为了好玩):

private void btnPlus_Click(object sender, EventArgs e)
{
    btnMinus.Enabled = true;
    if (f_intHoleNumber != 18) { f_intHoleNumber += 1; }
    if (f_intHoleNumber == 18) { btnPlus.Enabled = false; }
    txtHoleNumber.Text = f_intHoleNumber.ToString();            
}

I would like to refactor that and extract another method from it so I don't reuse code but i'm not sure if its possible to pass an operator (+=) as a parameter to a method.我想重构它并从中提取另一个方法,所以我不重用代码,但我不确定是否可以将运算符 (+=) 作为参数传递给方法。 Can this be done?这能做到吗?

I don't think so.我不这么认为。 What about passing +1 or -1 to the method and multiplying it with the value to add or to subtract.将 +1 或 -1 传递给该方法并将其与要添加或减去的值相乘怎么样? For example:例如:

public float calc(float val1, float val2, int op) 
{
    return val1 + op * val2;
}

You can pass a method that does the adding and subtracting for you.您可以传递一个为您进行加法和减法的方法。 You probably want to go that route.你可能想走那条路。 Pass Method as Parameter using C# 使用 C# 将方法作为参数传递

You could pass a Func<int, int> which accepts one int parameter and returns an int.您可以传递一个Func<int, int> ,它接受一个 int 参数并返回一个 int。

private void btnPlus_Click(object sender, EventArgs e)
{
    HandleHoleChange(currentHole => currentHole + 1);      
}

private void HandleHoleChange(Func<int, int> getNextHoleFunc)
{
    btnMinus.Enabled = true;
    if (f_intHoleNumber != 18) { f_intHoleNumber = getNextHoleFunc(f_intHoldNumber); }
    if (f_intHoleNumber == 18) { btnPlus.Enabled = false; }
    txtHoleNumber.Text = f_intHoleNumber.ToString();         
}

the accepted answer allows to pass a 0 which would mess up the calculation.接受的答案允许传递一个0 ,这会扰乱计算。 If you want only to allow for addition or subtraction you can use a boolean variable to specify it in the parameterlist:如果您只想允许加法或减法,您可以使用布尔变量在参数列表中指定它:

public float calc(float val1, float val2, bool add) 
{
    int op = add ? 1 : -1;
    return val1 + op * val2;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM