C# - 反射 - 获取所有索引中数组的属性

C# - Reflection - Get propriety of array in all index

我有两个类:

public class Car
{
    public string color { get; set; }
    public string model { get; set; }
}

public class myclass
{
    public Car[] car { get; set; }
}

和一个实例:

myclass c = new myclass()
{
    car = new Car[]
    {
        new Car()
        {
            color = "blue",
            model = "my model"
        },
        new Car()
        {
            color = "green",
            model = "my model 2"
        }
    }
};

var car = c.GetType().GetProperty("car").GetValue(c, null);

var 汽车 = :

如何遍历数组 car 的所有索引并获得 属性 color

如果你需要使用反射来做循环,你可以尝试这样的事情:

//gets the value of myclass's car property--an array of type Car[] returned as an object
var cars = c.GetType().GetProperty("car").GetValue(c, null);

if (cars.GetType().IsArray)//should be true for you
{
    //gets the type of the elements of the array: Car
    var carArrayElementType = cars.GetType().GetElementType();

    //gets the color property of Car
    var colorProp = carArrayElementType.GetProperty("color");

    //lets you loop through the cars array
    var carEnumerable = cars as IEnumerable;

    foreach (var car in carEnumerable)
    {
        //returns the color property's value as a string
        var color = colorProp.GetValue(car, null) as string;

       //use color
    }
}

就是说,循环遍历数组 car 的所有索引并获得 属性 color 而无需使用反射的更直接的方法是:

foreach(var car in c.car)
{
    var color = car.color;

    //use color
}

不确定你到底在问什么,从外观上看这与反射无关...如果你只是想遍历 c.car 中的所有汽车你可以使用 foreach 或 for 循环.

foreach (Car car in c.car)
{ Console.Writeline(car.color); }

for (int i = 0; i < c.car.length; ++i)
{ Console.Writeline(c.car[i].color); }

从表面上看,您还没有理解编程和 C# 属性的基础知识。我建议你找到一个代码风格并坚持下去,通常我会推荐 UpperCamelCase 用于属性和 类。你应该看看 microsofts documentation on properties

一种更通用的方法,将尝试将其转换为 IEnumerable 这样您的集合就不会单独绑定到数组。

var cars = c.GetType().GetProperty("car").GetValue(c) as IEnumerable<object>;
foreach (var car in cars)
{
    Console.WriteLine(car.GetType().GetProperty("color").GetValue(car));
}

我相信您只需将返回的对象从 GetValue 转换为 Car[] 数组,然后围绕它循环。

var cars = c.GetType().GetProperty("car").GetValue(c, null) as Car[];

foreach (Car c in cars)
{
   Debug.WriteLine("the color is " + c.color.ToString());
}