这是我的代码的一部分:
private void button1_Click(object sender, EventArgs e)
{
int Chocolate = int.Parse(QtyChocolate.Text);
TableUpdate("Chocolate", QtyChocolate.Text);
int Vanilla = int.Parse(QtyVanilla.Text);
TableUpate("Vanilla", QtyVanilla.Text);
int Strawberry = int.Parse(QtyStrawberry.Text);
TableUpate("Strawberry", QtyStrawberry.Text);
int Melon = int.Parse(QtyMelon.Text);
TableUpate("Melon", QtyMelon.Text);
int Mint = int.Parse(QtyMint.Text);
TableUpate("Mint", QtyMint.Text);
int Marijuana = int.Parse(QtyMarijuana.Text);
TableUpate("Marijuana", QtyMarijuana.Text);
Machinefunction1(a bunch of parameters here including some of the int ingredients);
Machinefunction55(a different bunch of parameters here including some of the int ingredients);
//...and hundreds more ingredients... These integer values parsed from corresponding
//textboxes will be used as parameters in various functions of the machine.
}
我正在尝试创建一种方法来简化代码,这是我尝试但失败的方法:
private void MyFunc(Ingredient, string text) //What method or keyword should precede Ingredient?
{
int Ingredient = int.Parse(text);
TableUpdate("Ingredient", text);
}
private void button1_Click(object sender, EventArgs e)
{
MyFunc(Chocolate, QtyChocolate.Text); //This will recall my method to produce the named integers
MyFunc(Vanilla, QtyVanilla.Text);
//...and so on...
Machinefunction1(a bunch of parameters here including some of the int ingredients);
Machinefunction55(a different bunch of parameters here including some of the int ingredients);
}
请帮忙,谢谢。对于造成的任何不便,我们深表歉意。
最佳答案
我建议你看看做这样的事情:
private void button1_Click(object sender, EventArgs e)
{
var ingredients = new Dictionary<string, int>()
{
{ "Chocolate", int.Parse(QtyChocolate.Text) },
{ "Vanilla", int.Parse(QtyVanilla.Text) },
{ "Strawberry", int.Parse(QtyStrawberry.Text) },
{ "Melon", int.Parse(QtyMelon.Text) },
{ "Mint", int.Parse(QtyMint.Text) },
{ "Marijuana", int.Parse(QtyMarijuana.Text) },
}
foreach (var ingredient in ingredients)
{
TableUpdate(ingredient.Key, ingredient.Value.ToString());
}
}
为每种成分使用单独的变量并使用 out
参数,虽然合法的 C#,通常只会使代码难以阅读。
关于c# - 在 C# 中重命名变量的用户定义方法中放置的正确方法或关键字是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50402927/