我正在为学校做一些练习,最后为列表框编写了一段代码,如下所示。现在注意3行代码总是在3个不同的私有中返回;
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
我想将它们放在某种功能或方法中,我可以简单地在需要此代码的每个私有部门中调用它但我不知道如何执行此操作,任何人都可以请我帮忙?
namespace IList
{
public partial class frmAddItem : Form
{
public frmAddItem()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
string newItem = txtItem.Text;
lstItems.Items.Add(newItem);
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
txtItem.Text = "";
}
private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
{
int Selected = lstItems.SelectedIndex;
Selected += 1;
string x = Selected.ToString();
txtSelected.Text = x;
}
private void btnRemoveAt_Click(object sender, EventArgs e)
{
int Location = int.Parse(txtRemoveAt.Text);
Location -= 1;
lstItems.Items.RemoveAt(Location);
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
}
private void btnClear_Click(object sender, EventArgs e)
{
lstItems.Items.Clear();
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
}
}
}
答案 0 :(得分:1)
实际上,这三行代码可以转换成一行代码,这样就无需将它们提取到一个独立的方法:
textAantal.Text = lstBox.Items.Count.ToString();
答案 1 :(得分:0)
编写一个如下所示的私有方法。
private void myActionMethod(string action)
{
switch (action)
{
case "btnAdd_Click"
string newItem = txtItem.Text;
lstItems.Items.Add(newItem);
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
txtItem.Text = "";
break;
case "lstItems_SelectedIndexChanged"
int Selected = lstItems.SelectedIndex;
Selected += 1;
string x = Selected.ToString();
txtSelected.Text = x;
break;
case "btnClear_Click"
int Location = int.Parse(txtRemoveAt.Text);
Location -= 1;
lstItems.Items.RemoveAt(Location);
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
break;
case "btnRemoveAt_Click"
int Location = int.Parse(txtRemoveAt.Text);
Location -= 1;
lstItems.Items.RemoveAt(Location);
int numberOfItems = lstItems.Items.Count;
string y = numberOfItems.ToString();
txtAantal.Text = y;
break;
}
}
在每个活动中调用您的方法
private void btnAdd_Click(object sender, EventArgs e)
{
myActionMethod("btnAdd_Click");
}
private void lstItems_SelectedIndexChanged(object sender, EventArgs e)
{
this. myActionMethod("lstItems_SelectedIndexChanged");
}
private void btnRemoveAt_Click(object sender, EventArgs e)
{
this. myActionMethod("btnRemoveAt_Click");
}
private void btnClear_Click(object sender, EventArgs e)
{
this. myActionMethod("btnClear_Click");
}
您可以将myActionMethod命名为任何名称MyUpdateMethod或其他名称。我希望这会有所帮助。