将对象类型值转换为类型,并通过Reflection从中获取值

时间:2012-03-02 21:53:40

标签: c# reflection

标题可能不是真正解释我需要的东西,但这里是样本:

这是我的模特:

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;
    }
}
我在这里所做的可能没有意义,但我需要在其他地方进行这种操作。我有一个Type和一个Object,我需要建立一个表格。在这个例子中,doWork方法与我在实际例子中处理的方法非常相似。

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

任何?

1 个答案:

答案 0 :(得分:1)

你尝试过这样的事吗?

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