首页 > 解决方案 > 使用 C# Visual Studio 将我的代码重写为方法

问题描述

我目前无法理解方法以及它们在 C# 中的工作方式。我目前为我创建的汽车成本计算器程序编写了代码,我想使用方法重新排列或分解我的代码。我不确定如何或从哪里开始这样做,因为它与我的程序有关。这是我的代码,澄清会有所帮助!谢谢!

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //constants for the Zone entered by user
    const decimal ZoneCostN = 27;
    const decimal ZoneCostS = 36;
    const decimal ZoneCostE = 45;
    const decimal ZoneCostW = 54;

    private void CalcButton_Click(object sender, EventArgs e)
    {
        //set the variables
        decimal PackWeight = 0;
        decimal CostZone = 0;
        decimal CostWeight = 0;
        decimal ShippingTot = 0;
        decimal Net = 0;
        const decimal PerPound = 18;

        //parses the entry into the textboxes
        decimal.TryParse(WeightText.Text, out PackWeight); ;

        //algorithm for variables
        CostWeight = PackWeight * PerPound;
        Zonelbl.Text = "";
        CostZone = 0;

        //if else statement to get the zone cost
        {
            if (NorthButton.Checked)
            {
                CostZone = ZoneCostN;
            }
            else if (SouthButton.Checked)
            {
                CostZone = ZoneCostS;
            }
            else if (EastButton.Checked)
            {
                CostZone = ZoneCostE;
            }
            else if (WestButton.Checked)
            {
                CostZone = ZoneCostW;
            }
            else
            {
                MessageBox.Show("Select a zone!");
            }
        }
        //algorithm to get total and net
        ShippingTot = CostZone + CostWeight;
        Net = ShippingTot / CostWeight;

        //if condition for CAPPED label
        if (ShippingTot >= 100)
        {
            CAPPEDlbl.Visible = true;
        }
        else
        {
            CAPPEDlbl.Visible = false;
        }

        //output for all the data
        Zonelbl.Text = CostZone.ToString("c");
        Weightlbl.Text = CostWeight.ToString("c");
        Totallbl.Text = ShippingTot.ToString("c");
        Netlbl.Text = Net.ToString("c");
    }

    private void ClearButton_Click(object sender, EventArgs e)
    {
        //clears the form
        Zonelbl.Text = "";
        Weightlbl.Text = "";
        Totallbl.Text = "";
        Netlbl.Text = "";
        WeightText.Text = "";
        CAPPEDlbl.Visible = false;
        WeightText.Focus();
    }
}

标签: c#visual-studiowinformsmethodsparameter-passing

解决方案


通常,当我们需要重用代码时,我们会创建方法。在您的情况下,您应该看到将来会重用代码的哪一部分。如果它是一个简单的表单,您可能不需要更改任何内容,但想象您想在其他地方使用您的清晰功能,创建一个方法并在您需要的任何地方调用它

        void clear()
    {
        Zonelbl.Text = "";
        Weightlbl.Text = "";
        Totallbl.Text = "";
        Netlbl.Text = "";
        WeightText.Text = "";
        CAPPEDlbl.Visible = false;
        WeightText.Focus();
    }


    private void ClearButton_Click(object sender, EventArgs e)
{
    clear();
}

现在您可以重用 clear() ,如果您需要更改它,您只需要更改方法。这是一个概念,您可以在任何需要的地方应用它。


推荐阅读