在List< T>中访问对象的属性. [英] Accessing properties of objects within a List<T>

查看:65
本文介绍了在List< T>中访问对象的属性.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用存储在List<T>对象中的各个对象实例的属性,但是我似乎无法直接访问这些属性.

I'm trying to use a property of individual object instances stored within a List<T> object, but I can't seem to access the properties directly.

我有一个对象(sportsCarVehicle),该对象在其内部存储了用户定义的名称(strVehicleName)(以及其他属性,但这并不重要).然后将该对象存储在名为sportsCarVehicleStorageList<sportsCarVehicle>对象中.
我需要访问List<sportsCarVehicle>sportsCarVehicle的每个实例,并将strVehicleName的值传递给表单上的组合框.

I have an object (sportsCarVehicle) which stores a user-defined name (strVehicleName) (amongst other properties, but that's not important) within itself. The object is then stored within a List<sportsCarVehicle> object called sportsCarVehicleStorage.
I need to access every instance of sportsCarVehicle in List<sportsCarVehicle> and pass the value of strVehicleName to a combo box on a form.

我假设我需要某种循环来遍历每个实例并将名称传递给组合框,但是我的主要问题是无法访问所需的属性. sportsCarVehicle实例没有可引用的名称.
我还要注意一件事:sportsCarVehicleStorage.Add()的构造函数在sportsCarVehicleStorage.Add()方法中调用.

I assume I'll need some kind to loop to cycle through each instance and pass the name to the combo box, but my main issue is not being able to access the property I need. The sportsCarVehicle instances have no reference-able name.
One more thing I should note: the constructor for sportsCarVehicle is called within the sportsCarVehicleStorage.Add() method.

关于我该怎么做的任何建议?

Any suggestions on how I could do this?

推荐答案

不能这样做

List<string> lst = new List<string>{"Hello", "World"};

 int len = lst[0].Length;

此处.Length是字符串的属性.只要该财产是公共的,我们就可以访问它.

Here .Length is a property of string. As long as that property is public we can access it.

以您的情况

List<sportsCarVehicle> sportsCarVehicleStorage = new List<sportsCarVehicle>();

// Some code to populate list.

mycombobox.Items = sportsCarVehicleStorage
                   .Select(x => x.strVehicleName).ToArray();

确保属性strVehicleName在该类中是公共的.

Make Sure property strVehicleName is public in that class.

这篇关于在List&lt; T&gt;中访问对象的属性.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆