检查作为对象列表的 Class-属性 的属性

Check Properties of a Class-Property that is a List of objects

我有一个 class,一些 class 属性是 class 的列表。我现在想 运行 遍历列表中的所有元素。但无论我尝试什么,我都无法抓住列表中的对象。有人能解决我的问题吗?

 public class car 
 {
    public int id {get; set;}
    public Tire attribute {get; set;}
 }

 public class Tire
 {
    public int id {get; set;}
    public double value {get; set;}
 }

这里是我的主程序,它创建了一些 classes 和列表:

 public class Program
 {
    static void Main(string[] args)
    {
       Tire black = new Tire()
       {
          id = 5
       };
       Tire red = new Tire()
       {
          id = 8
       };
       Tire purple = new Tire()
       {
          id = 10
       };

       //Create my List
       List<Tire> mylist = new List<Tire>();
       List.Add(black);
       List.Add(red);
       List.Add(purple);


       //Define the car
       car mycar = new car()
       {
          id = 20,
          Tire = mylist
       };

我现在想 运行 遍历我的 Tire-属性-列表中的所有元素,但无论我做什么,我都无法在列表中获得实际对象(黑色、红色和紫色)​​- 属性。 这是我到目前为止尝试过的:

var type = car.GetType();
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
    if (propertyInfo.ToString().Contains("List"))
    {
        var propValue = propertyInfo.GetValue(this);
        ...

如果我调试并查看 propValue 变量,我会看到我所有的三个对象,但我无法找到一种方法来实际检查它们并再次获取它们的属性...

简单的怎么样

foreach (var tire in car.attributes)
{ 
    // tire is an instance of the Tire class
}

你的实现有很多问题:

当您填充列表时:

//Create my List
List<Tire> mylist = new List<Tire>();
List.Add(black);
List.Add(red);
List.Add(purple);

如果您想在列表中添加您的轮胎,应该是:

//Create my List
List<Tire> mylist = new List<Tire>();
mylist.Add(black);
mylist.Add(red);
mylist.Add(purple);

在你的class结构中

你的车有几个轮胎,对吧?所以 class 应该有一个轮胎列表,而不仅仅是一个轮胎:

public class Car 
{
    public int Id {get; set;}
    public List<Tire> TireList {get; set;}
}

当你想实例化你的汽车时

您的 mylist 在构造函数调用中不可访问,您必须在调用构造函数后对其进行设置(或创建一个可以在参数中包含轮胎列表的构造函数):

//Define the car
Car mycar = new Car()
{
    Id = 20
};

mycar.TireList = mylist;

快速工作演示

我没有解决所有问题,但这里有一个工作示例 (ConsoleApp):

class Program
{
    static void Main(string[] args)
    {
        Tire black = new Tire()
        {
            Id = 5
        };
        Tire red = new Tire()
        {
            Id = 8
        };
        Tire purple = new Tire()
        {
            Id = 10
        };

        //Create my List
        List<Tire> mylist = new List<Tire>();
        mylist.Add(black);
        mylist.Add(red);
        mylist.Add(purple);


        //Define the car
        Car mycar = new Car()
        {
            Id = 20
        };

        mycar.TireList = mylist;

        foreach (var tire in mycar.TireList)
        {
            Console.WriteLine(tire.Id);
        }

        Console.ReadKey();
    }
}

public class Car
{
    public int Id { get; set; }
    public List<Tire> TireList { get; set; }
}

public class Tire
{
    public int Id { get; set; }
    public double Value { get; set; }
}

备注

最后但同样重要的是,在对象名称中使用大写要小心