访问List 中的对象属性
我正在尝试使用存储在List
对象中的单个对象实例的属性,但我似乎无法直接访问属性。
我有一个对象( sportsCarVehicle
),它存储一个用户定义的名称( strVehicleName
)(在其他属性中,但这并不重要)。 然后将对象存储在名为sportsCarVehicleStorage
的List
对象中。
我需要访问List
的sportsCarVehicle
每个实例, sportsCarVehicle
List
的值传递给strVehicleName
上的combobox。
我假设我需要某种循环来遍历每个实例并将名称传递给combobox,但我的主要问题是无法访问我需要的属性。 sportsCarVehicle
实例没有可引用的名称。
还有一点需要注意: sportsCarVehicle
的构造函数在sportsCarVehicleStorage.Add()
方法中调用。
有关如何做到这一点的任何建议?
你不能这样做
List lst = new List {"Hello", "World"}; int len = lst[0].Length;
这里.Length
是字符串的属性。 只要该财产是公开的,我们就可以访问它。
在你的情况下
List sportsCarVehicleStorage = new List (); // Some code to populate list. mycombobox.Items = sportsCarVehicleStorage .Select(x => x.strVehicleName).ToArray();
Make Sure属性strVehicleName
在该类中是公共的。
您可以使用foreach
循环遍历列表,将列表的每个成员分配给命名变量,如:
foreach (sportsCarVehicle scv in sportsCarVehicleStorage) { //scv is the name of the currently looping sportsCarVehicle object //use scv.strVehicleName to access the property. myComboBox.Items.Add(scv.strVehicleName); }
foreach (SportsCarVehicle car in myListName) { //do stuff here }
这是最基本的例子,您可以使用PLINQ等以更简化的方式进行。
另一种方法是将sportsCarVehicle列表直接绑定到comboBox,例如:
List sportsCarVehicleStorage= new List; // Set up list content here // ... myComboBox.DataSource = sportsCarVehicleStorage; myComboBox.DisplayMember = "strVehicleName";