c# - 使用 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();
}
}
解决方案
通常,当我们需要重用代码时,我们会创建方法。在您的情况下,您应该看到将来会重用代码的哪一部分。如果它是一个简单的表单,您可能不需要更改任何内容,但想象您想在其他地方使用您的清晰功能,创建一个方法并在您需要的任何地方调用它
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() ,如果您需要更改它,您只需要更改方法。这是一个概念,您可以在任何需要的地方应用它。
推荐阅读
- android - 使用 smalidea 在 Intellij 调试器中调试 smali 代码时访问虚拟寄存器
- ionic2 - 我无法使用来自 ios 的 facebook 验证 myapp
- r - 如何构造amxm相关矩阵
- android - Android Studio 的 logcat 在具有 Lollipop(5.1) 的 Gionee P5W 中运行应用程序时显示“Error inflating class EditText”
- regex - 如何分离正则表达式并获得每一次出现?
- qt - 如何在代码片段中获取当前文件名
- python - 如何在 softmax 分数中添加阈值
- python-2.7 - 将 Python(2.7) 字典转换为有效的查询参数
- javascript - Solidity 中的参数数量无效
- c# - 根据架构验证 XML 文件会引发异常