因此,我的问题可能会变得很简单。我知道如何创建一个方法来从应用程序回调,但我的问题是试图找出如何正确地做到这一点。我需要重复foreach循环:(foreach(Ticket t in events) if(t.getName()。Equals(cbEvents.SelectedItem.ToString())) { ) 并将其更改为在代码中调用两次的方法。请帮忙。下面的代码。将一个重复的foreach循环转到一个方法,以便它只重复一次
using System;
using System.Collections;
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 TicketPurchasing
{
public partial class Form1 : Form
{
private ArrayList events;
public Form1()
{
InitializeComponent();
events = new ArrayList();
}
private void Form1_Load(object sender, EventArgs e)
{
//Create events
events.Add(new Game(12.00, "KSU vs UGA", "Convocation Building", "bball", "Basketball"));
events.Add(new Game(15.00, "KSU vs GSU", "Stadium", "fball", "Football"));
events.Add(new Concert(8.00, "Country Music", "Campus Green", "hayes", "Hunter Hayes"));
events.Add(new Concert(12.00, "Rock/Pop", "Campus Green", "m5", "Maroon5"));
//Load combobox
foreach (Ticket t in events)
{
cbEvents.Items.Add(t.getName());
}
}
private void btnDetails_Click(object sender, EventArgs e)
{
//Get name of selected item from combobox
string eventName;
//Traverse array to determine the match
foreach (Ticket t in events)
{
if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
{
//Display details
lblDetails.Text = t.getDetails();
//Display image
displayImage(t.getFileName());
}
}
}
private void displayImage(string file)
{
Size size = new Size(173, 180);
Image img = (Image)Properties.Resources.ResourceManager.GetObject(file);
img = (Image)(new Bitmap(img, size));
pbImage.Image = img;
pbImage.Refresh();
pbImage.Visible = true;
}
private void txtTickets_TextChanged(object sender, EventArgs e)
{
//Get number of tickets
int num = int.Parse(txtTickets.Text);
double ticketCost = 0;
//Get cost of ticket
foreach (Ticket t in events)
{
if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
{
ticketCost = t.getCost();
}
}
//Calculate cost
double total = num * ticketCost;
//Display cost
txtCost.Text = total.ToString("c");
}
private void btnExit_Click(object sender, EventArgs e)
{
//Exit the application
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
//Clear all information
lblDetails.Text = "";
pbImage.Image = null;
txtTickets.Text = "0";
txtCost.Text = "";
}
}
}
你能更具体一点吗?你想要将你的foreach代码封装到可重用的方法中,或者只是让if可重用? – mikes
你的意思是你只需要重构它,所以你可以调用dothis或其他? – BugFinder
您可以使用委托调用方法。并在方法中循环遍历元素并调用委托。代表可以在你的foreach块中包含你的代码行。 –