使用反射映射类的所有属性

时间:2012-07-26 07:14:23

标签: asp.net system.reflection

我有两个域类

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }

}
public class Address
{
    public string HouseName { get; set; }
    public string StreetName { get; set; }
    public string PinCode { get; set; }
}

我想将Employee类的对象映射到另一个类。 我使用反射将empData对象映射到另一个对象。我使用的代码是

private void GetValues(object empData)
{
    System.Type type = empData.GetType();

    foreach (PropertyInfo pInfo in type.GetProperties())
    {
        //do some stuff using this pInfo. 
    }
}

我可以轻松映射emp对象中除Address属性之外的所有属性,该对象是另一个类的对象。 那么我如何映射所有属性而不管其类型?即,如果地址包含另一个类的对象,它也应该被映射。

3 个答案:

答案 0 :(得分:1)

你不能使用AutoMapper来映射类吗?

答案 1 :(得分:0)

您可以通过

了解要映射的属性类型
if (propertyInfo.PropertyType == typeof(Address))
    { // do now get all properties of this object and map them}

答案 2 :(得分:0)

假设您希望能够在任何类型的对象上执行此操作,而不仅仅是这个特定的对象,您应该使用某种递归解决方案。但是,如果只是为了这个对象 - 为什么你甚至使用反射?对我来说,它只是增加了不必要的复杂性,就像将六个属性映射到另一组对象一样简单。

如果您希望获得有关代码示例的更具体帮助,则必须为我们提供更多上下文。为什么名为“GetValues”的方法的返回类型为void?我很难编写一个例子来记住这一点。 :)

相关问题