使用 foreach 循环从数组中检索值
本文关键字:检索 数组 foreach 循环 使用 | 更新日期: 2023-09-27 18:33:20
我使用 foreach 循环时创建的 3 个不同类向数组添加了多个值,我只从第一个类中获取值 有什么方法可以在多个类上使用foreach吗?
AdvertDao advert = new AdvertDao();
var array = new ArrayList();
array = advert.fillAdvert();
foreach (Member m in array)
{
txtBoxEmail.Text = m.Email;
txtBoxPhone.Text = m.Phone.ToString();
txtBoxUsername.Text = m.Username;
}
foreach (Consoles c in array)
{
cmbConsole.Text = c.ConsoleName;
}
foreach (Advert a in array)
{
cmbGenre.Text = a.Genre;
lblDateStarted.Text = a.Date.ToString("dd/MM/yyyy");
txtBoxPrice.Text = a.Price.ToString();
txtBoxName.Text = a.Name;
txtBoxDesc.Text = a.Description;
}
fillAdvert()
方法:
public ArrayList fillAdvert()
{
Member member = new Member();
Advert advert = new Advert();
Consoles console = new Consoles();
Picture picture = new Picture();
ArrayList advertList = new ArrayList();
if (!DatabaseConnection.IsOpen)
{
DatabaseConnection.Open();
}
OracleCommand cmd = new OracleCommand();
cmd.Connection = DatabaseConnection.Connection;
string str = "SELECT * FROM ADVERT_ADPIC_MEMBER_CONSOLE WHERE username = '" + GlobalVariables.Username + "' AND name = '" + GlobalVariables.SellingName + "'";
cmd.CommandText = str;
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
member.Username = dr.GetString(0);
member.MemberID = dr.GetInt32(1);
member.Phone = dr.GetInt32(2);
member.Email = dr.GetString(3);
console.ConsoleName = dr.GetString(5);
advert.Description = dr.GetString(6);
advert.Genre = dr.GetString(7);
advert.Date = dr.GetDateTime(8);
advert.Price = dr.GetDouble(9);
advert.Name = dr.GetString(4);
advertList.Add(member);
advertList.Add(console);
advertList.Add(advert);
}
return advertList;
}
可能是一种更简单的方法,但这是他们希望在大学里完成的方式。
可以使用一个以 object
为元素类型的foreach
块,但需要检查元素的类型,将元素转换为正确的类型,并根据元素的类型实现逻辑。
foreach (object obj in array)
{
if (obj is Member)
{
Member m = (Member)obj;
txtBoxEmail.Text = m.Email;
txtBoxPhone.Text = m.Phone.ToString();
txtBoxUsername.Text = m.Username;
}
else if (obj is Consoles)
{
Consoles c = (Consoles)obj;
cmbConsole.Text = c.ConsoleName;
}
else if (obj is Advert)
{
Advert a = (Advert)obj;
cmbGenre.Text = a.Genre;
lblDateStarted.Text = a.Date.ToString("dd/MM/yyyy");
txtBoxPrice.Text = a.Price.ToString();
txtBoxName.Text = a.Name;
txtBoxDesc.Text = a.Description;
}
}
foreach 循环要求对象实现 System.Collections.IEnumerable
或 System.Collections.Generic.IEnumerable 接口。
所以,答案是否定的没有直接的方法可以在 foreach 循环中使用多个对象。
执行所需操作的一种方法是使用接口和 foreach 循环,前提是使三个类实现相同的接口。
public interface IInterface
{
string Text { get; }
}
然后,如果你在每个类中实现这个接口,你可以做如下的事情:
foreach (IInterface i in array)
{
//do whatever you want with the text here.
}
但是,您将只能使用在界面中实现的属性。因此,如果您需要根据对象"不同"的属性,除了必须在接口中实现所有必需的属性之外,您还必须使用某种类型的指示符并在循环中使用 if 或开关。