将Object Type值强制转换为Type,然后通过Reflection从中获取value

本文关键字:Type Reflection value 获取 然后 Object 转换 | 更新日期: 2023-09-27 18:26:34

标题可能不是真正解释我需要什么,但这里是示例:

这是我的型号:

public class Car {
    public int CarId { get; set; }
    public string Name { get; set; }
    public string Model { get; set; }
    public string Make { get; set; }
}

逻辑如下:

class Program {
    static void Main(string[] args) {
        var cars = new List<Car> { 
            new Car { CarId = 1, Make = "Foo", Model = "FooM", Name = "FooN" },
            new Car { CarId = 2, Make = "Foo2", Model = "FooM2", Name = "FooN2" }
        }.AsQueryable();
        doWork(cars.GetType(), cars);
    }
    static void doWork(Type type, object value) {
        if (isTypeOfIEnumerable(type)) {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine(
                string.Join<string>(
                    " -- ", itemType.GetProperties().Select(x => x.Name)
                )
            );
            //How to grab values at the same order as properties? 
            //E.g. If Car.Name was pulled first, 
            //then the value of that property should be pulled here first as well
        }
    }
    static bool isTypeOfIEnumerable(Type type) {
        foreach (Type interfaceType in type.GetInterfaces()) {
            if (interfaceType.IsGenericType &&
                    interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                return true;
        }
        return false;
    }
}

我在这里做的可能没有意义,但我需要在其他地方做这种手术。我有一个TypeObject,我需要用它来构建一个表。在这个例子中,doWork方法和我在实际例子中处理的方法非常相似。

我设法提取了属性名称,但找不到任何从value参数中检索值的方法。

有人吗?

将Object Type值强制转换为Type,然后通过Reflection从中获取value

你试过这样的东西吗?

obj.GetType().GetProperties()
   .Select(pi => new { Name = pi.Name, Value = pi.GetValue(obj, null) })