當涉及到c#時,我是一個完整的newb,並且在過去4個小時試圖創建一個方法而不是使用多個if/else語句的過程中掙扎。有人可以指出我的寫作方向嗎?如何使用我現有的代碼創建方法
基本上下面的代碼有5個輸入,當點擊button1時將計算它們的平方根。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace sqRoot
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void gatherTextBoxData()
{
double[] _lookup = new double[5];
double doubleUserInput1;
double doubleUserInput2;
double doubleUserInput3;
double doubleUserInput4;
double doubleUserInput5;
if (Double.TryParse(textBox1.Text, out doubleUserInput1))
{
double doubleUserSqRoot1 = Math.Sqrt(doubleUserInput1);
label2.Text = Convert.ToString(doubleUserSqRoot1);
}
else
{
label2.Text = textBox1.Text + " is not a number";
}
if (Double.TryParse(textBox2.Text, out doubleUserInput2))
{
double doubleUserSqRoot2 = Math.Sqrt(doubleUserInput2);
label3.Text = Convert.ToString(doubleUserSqRoot2);
}
else
{
label3.Text = textBox2.Text + " is not a number";
}
if (Double.TryParse(textBox3.Text, out doubleUserInput3))
{
double doubleUserSqRoot3 = Math.Sqrt(doubleUserInput3);
label4.Text = Convert.ToString(doubleUserSqRoot3);
}
else
{
label4.Text = textBox3.Text + " is not a number";
}
if (Double.TryParse(textBox4.Text, out doubleUserInput4))
{
double doubleUserSqRoot4 = Math.Sqrt(doubleUserInput4);
label5.Text = Convert.ToString(doubleUserSqRoot4);
}
else
{
label5.Text = textBox4.Text + " is not a number";
}
if (Double.TryParse(textBox5.Text, out doubleUserInput5))
{
double doubleUserSqRoot5 = Math.Sqrt(doubleUserInput5);
label6.Text = Convert.ToString(doubleUserSqRoot5);
}
else
{
label6.Text = textBox4.Text + " is not a number";
}
}
private void button1_Click(object sender, EventArgs e)
{
gatherTextBoxData();
}
}
}
這個問題將是對codereview.stackexchange.com – pstrjds