有没有缩短需要变量的代码?

时间:2017-12-10 04:02:35

标签: c#

我一直在想,有没有办法缩短这种代码?

private void Update01()
{
    item01.text = item01n + "\nCost: " + Math.Round(cost01, 2) + "\nYou have: " + n01;
}

private void Update02()
{
    item02.text = item02n + "\nCost: " + Math.Round(cost02, 2) + "\nYou have: " + n02;
}

private void Update03()
{
    item03.text = item03n + "\nCost: " + Math.Round(cost03, 2) + "\nYou have: " + n03;
}
.
.
.

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如12秒所述,只返回一个字符串并传入3个变量:

private string GetUpdate(item, cost, n)
{
    return item + "\nCost: " + Math.Round(cost, 2) + "\nYou have: " + n;
}

然后简单地做:

item01.text = GetUpdate(item01n, cost01, n01);
item02.text = GetUpdate(item02n, cost02, n02);
item03.text = GetUpdate(item03n, cost03, n03);