在C#中,可以使用反射和递归的方式将嵌套对象转换为对象。下面是一个示例代码:
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
对象。最后,我们打印了转换后的对象的属性值。
这种方法可以适用于任意嵌套层级的对象转换,并且可以处理不同类型的属性。
领取专属 10元无门槛券
手把手带您无忧上云