我的问题很简单,但我不知道如何解决它。
如果我已经确定创建了多少个无人机,我的代码就可以工作了。
INICIO
公共部分类Inicio:表格{
私人的 无人机 </跨度> d1’,d2; 私人竞技场;
公共Inicio() { 的InitializeComponent(); }
private void btnconetar_Click(object sender,EventArgs e) { d1 =新的 无人机 </跨度> 鈥
如果您拥有未知数量的无人机,那么您希望使用集合类型而不是不同的字段:
public partial class Inicio : Form { private List<Drone> drones; private Arena arena; ... public partial class Arena : Form { private List<Drone> drones; public Arena(IEnumerable<Drone> drones) { InitializeComponent(); drones = new List<Drone>(drones); } ...
你需要有一个无人机列表,所以使用 List<Drone> 。然后将该列表传递给您 Arena :
List<Drone>
Arena
public partial class Inicio : Form { private List<Drone> drones; private Arena arena; public Inicio() { InitializeComponent(); this.drones = new List<Drone>(); } private void btnconetar_Click(object sender, EventArgs e) { d1 = new Drone( "192.168.1.10" ); d2 = new Drone( "192.168.1.20" ); drones.Add( d1 ); drones.Add( d2 ); // more drones arena = new Arena( drones ); arena.Show(); this.Hide(); } }
在你的 Arena 将组合框的数据源设置为 List<Drone> 。组合框改变后,你可以得到 SelectedItem 它将选择无人机对象。我还将展示如何在需要时获取代码中的其他值。您不应该循环并搜索所选项目。
SelectedItem
public partial class Arena : Form { private List<Drone> drones; public Arena(List<Drone> drones) { InitializeComponent(); this.drones = drones; cb_drone.DataSource = drones; // This should be whatever the property name is in your drone class cb_drones.ValueMember = "DroneIp"; // THis should be whatever the property name is // in your drone class that you want to display to the user cb_drones.DisplayMember = "DroneSomething"; } private void cb_drone_SelectedIndexChanged(object sender, EventArgs e) { // will give you the drone object var selectedDrone = cb_drone.SelectedItem; // var value = cb_drone.SelectedValue; will give you the Ip (whatever you specified in ValueMember) // var selectedDrone = this.drones.Where(x => x.DroneIp == cb_drone.SelectedValue) //do something with selectedDrone or the other things } }
请在构造函数中使用'params'关键字:
public partial class Arena : Form { private readonly Drone[] d; public Arena(params Drone[] d) { InitializeComponent(); this.d = d; } private void cb_drone_SelectedIndexChanged(object sender, EventArgs e) { foreach (var di in this.d) { if(cb_drone.SelectedIndex.ToString() == di.ip_drone) { //do something } } } }
这样你可以像这样使用它(当你已经知道它们的数量时)
public partial class Inicio : Form { private Drone d1,d2; private Arena arena; public Inicio() { InitializeComponent(); } private void btnconetar_Click(object sender, EventArgs e) { d1 = new Drone("192.168.1.10"); d2 = new Drone("192.168.1.20"); .... dn = new Drone("192.168.1.xx"); arena = new Arena(d1,d2); arena.Show(); this.Hide(); } }
或者如果你不知道它们中有多少
public partial class Inicio : Form { private List d; private Arena arena; public Inicio() { InitializeComponent(); } private void btnconetar_Click(object sender, EventArgs e) { d = new List(){ new Drone("192.168.1.10"), /* whatever */ }; arena = new Arena(d.ToArray()); arena.Show(); this.Hide(); } }