Skip to main content
 首页 » 编程设计

c#之如何在文本框中显示所有 Listclass> 属性

2024年02月13日13unruledboy

我试图在 C# 中的 TextBox 中显示所有对象属性。

当我有一个带有属性的类时:

public class Person 
{ 
    public int ID;  
    public string name; 
    public int Age; 
} 

我有一个对象列表:

List<Person> PersonList = new List<Person>(); 

填写人:

Person Person1 = new Person(); 
Person1.ID = 1; 
Person1.name = "John"; 
Person1.Age = 20; 
 
Person Person2 = new Person(); 
... 
PersonList.Add(Person1); 
PersonList.Add(Person2); 
PersonList.Add(Person3); 

我必须显示例如。这些对象的所有年龄都来自 TextBox 中的 PersonList。

我不知道如何从此列表中的所有对象获取 Age 属性,我尝试了:

this.textBox2.Text = ("Found Ages: " + string.Join(" ", PersonList)); 

但它没有显示我需要的内容。

也许是 foreach 循环?

请您参考如下方法:

您可以根据需要使用 LINQ:

this.textBox2.Text = ("Found Ages: " + string.Join(" ", PersonList.Select(x=>x.Age)); 

注意 如果不存在,您必须在源代码文件的顶部使用using System.Linq;。