在 C# 中访问 List
本文关键字:对象 属性 包含 Object 访问 List | 更新日期: 2023-09-27 18:37:14
我似乎无法弄清楚如何访问列表中包含的每个对象的特定属性。例如,如果我在列表之外引用对象(在将其传递给按钮单击之前),我可以看到"标签"、"高度"、"宽度"等属性(该类型的所有标准属性)。但是,一旦列表传递给我的按钮单击事件,我就无法弄清楚如何访问这些特定于对象的属性。
请参考这个例子:
private TextBox createTextBox(string name)
{
// Create TextBox Code is Here
TextBox dTextBox = new TextBox();
dTextBox.Name = name;
dTextBox.Tag = "sometag";
dTextBox.Height = 12345;
dTextBox.Width = 12345;
return dTextBox;
}
private void some_function()
{
var objectList = new List<Object>();
objectList.Add(createTextBox("example1"));
objectList.Add(createTextBox("example2"));
objectList.Add(createTextBox("example3"));
}
private int button_click(object sender, EventArgs e, Int32 ticketGroupID, List<Object> objectList)
{
for(int i = 0; i < objectList.Count(); i++)
{
Int32 valuableInfo = objectList[i].?? // Here is where I am trying to access specific properties about the object at index i in the list, such as the objects TAG, VALUE, etc. How can this be done?
// do things with the valuable info
};
}
提前感谢任何帮助。
您需要使object
成为强类型。也就是说,将其投射到您的class
:
Int32 valuableInfo = ((TextBox)objectList[i]).Height; //now you can access your property
否则,您将无法访问类的属性,因为编译器不知道object
的实际类型是什么。此外,您的智能感知只会将其视为object
,而不是您的强类型类(例如:MyClass
,或者在您的情况下,类TextBox
它是一个
列表<>它实现了IEnumerable<T>
,因此您可以使用OfType<T>()
方法来提取已经强类型并准备好供您访问的项目:
var myListOfTypedObjects = myList.OfType<TextBox>();
myListOfTypedObjects.ForEach(tb => Console.Writeline(tb.Name));
您可以
先检查type
,然后再将其转换为TextBox
或反向检查。
请参阅以下示例:
foreach (var obj in objectList)
{
// method 1: check first, cast later
if (obj is TextBox)
{
Int32 valueableInfo = ((TextBox)obj).Height;
}
// method2: cast first, check later
var textBox = obj as TextBox;
if (obj != null)
{
Int32 valueableInfo = obj.Height;
}
}