c# - 在 C# 中重命名变量的用户定义方法中放置的正确方法或关键字是什么?

标签 c# parsing variables int user-defined

这是我的代码的一部分:

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/

相关文章:

java - 为什么不能创建没有花括号的 1 语句函数?

parsing - 基于 LLVM 的编译器的前端

java - 使用 JSON 解析获取 OpenWeathermapApi 数据

c# - 将日期时间转换为日期格式 dd/mm/yyyy

c# - Web API + HttpClient : An asynchronous module or handler completed while an asynchronous operation was still pending

c# - XDocument Root.Elements() 返回 null

java最终数组小写或大写

javascript - 如何在 PEG 语法中描述函数参数

JavaScript OR (||) 短路奇怪行为

debugging - 当前上下文中没有全局变量(或宏)的符号