首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中将嵌套对象转换为对象

在C#中,可以使用反射和递归的方式将嵌套对象转换为对象。下面是一个示例代码:

代码语言:txt
复制
using System;
using System.Reflection;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

public static class ObjectConverter
{
    public static T Convert<T>(object source) where T : new()
    {
        Type targetType = typeof(T);
        T target = new T();

        foreach (PropertyInfo sourceProperty in source.GetType().GetProperties())
        {
            PropertyInfo targetProperty = targetType.GetProperty(sourceProperty.Name);

            if (targetProperty != null && targetProperty.CanWrite)
            {
                object sourceValue = sourceProperty.GetValue(source);
                object targetValue;

                if (sourceValue != null && sourceProperty.PropertyType != targetProperty.PropertyType)
                {
                    targetValue = Convert(sourceValue, targetProperty.PropertyType);
                }
                else
                {
                    targetValue = sourceValue;
                }

                targetProperty.SetValue(target, targetValue);
            }
        }

        return target;
    }

    private static object Convert(object source, Type targetType)
    {
        MethodInfo convertMethod = typeof(ObjectConverter).GetMethod("Convert").MakeGenericMethod(targetType);
        return convertMethod.Invoke(null, new object[] { source });
    }
}

public class Program
{
    public static void Main()
    {
        var nestedObject = new
        {
            Name = "John",
            Age = 30,
            Address = new
            {
                Street = "123 Main St",
                City = "New York"
            }
        };

        Person person = ObjectConverter.Convert<Person>(nestedObject);

        Console.WriteLine($"Name: {person.Name}");
        Console.WriteLine($"Age: {person.Age}");
        Console.WriteLine($"Street: {person.Address.Street}");
        Console.WriteLine($"City: {person.Address.City}");
    }
}

上述代码中,我们定义了一个Person类和一个Address类,Person类包含一个Address对象作为属性。然后,我们创建了一个ObjectConverter类,其中的Convert方法使用反射和递归的方式将嵌套对象转换为目标类型的对象。

Main方法中,我们创建了一个嵌套对象nestedObject,然后使用ObjectConverter.Convert<Person>(nestedObject)将其转换为Person对象。最后,我们打印了转换后的对象的属性值。

这种方法可以适用于任意嵌套层级的对象转换,并且可以处理不同类型的属性。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券