繁体   English   中英

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

[英]Cast Object Type value into a Type and get Values out of it by 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参数中检索值的任何方法。

任何人?

你尝试过这样的事情吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM