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

C# -将属性路径列表及其值动态转换为类对象

在C#中,可以使用反射和递归的方式将属性路径列表及其值动态转换为类对象。以下是一个示例代码,展示了如何实现这个功能:

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

public class MyClass
{
    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 ConvertToObject<T>(string[] propertyPaths, object[] propertyValues) where T : class, new()
    {
        if (propertyPaths.Length != propertyValues.Length)
        {
            throw new ArgumentException("The number of property paths and property values must be equal.");
        }

        T obj = new T();
        Type objectType = typeof(T);

        for (int i = 0; i < propertyPaths.Length; i++)
        {
            SetProperty(objectType, obj, propertyPaths[i], propertyValues[i]);
        }

        return obj;
    }

    private static void SetProperty(Type objectType, object obj, string propertyPath, object propertyValue)
    {
        string[] properties = propertyPath.Split('.');
        PropertyInfo propertyInfo = objectType.GetProperty(properties[0]);

        if (propertyInfo == null)
        {
            throw new ArgumentException($"Property '{properties[0]}' does not exist in type '{objectType.Name}'.");
        }

        if (properties.Length > 1)
        {
            object nestedObj = propertyInfo.GetValue(obj);
            if (nestedObj == null)
            {
                nestedObj = Activator.CreateInstance(propertyInfo.PropertyType);
                propertyInfo.SetValue(obj, nestedObj);
            }

            SetProperty(propertyInfo.PropertyType, nestedObj, string.Join(".", properties, 1, properties.Length - 1), propertyValue);
        }
        else
        {
            if (propertyInfo.PropertyType != propertyValue.GetType())
            {
                throw new ArgumentException($"Value type '{propertyValue.GetType().Name}' does not match property type '{propertyInfo.PropertyType.Name}'.");
            }

            propertyInfo.SetValue(obj, propertyValue);
        }
    }
}

public class Program
{
    public static void Main()
    {
        string[] propertyPaths = { "Name", "Age", "Address.Street", "Address.City" };
        object[] propertyValues = { "John Doe", 30, "123 Main St", "New York" };

        MyClass obj = ObjectConverter.ConvertToObject<MyClass>(propertyPaths, propertyValues);

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

在上面的示例代码中,我们定义了一个MyClass类和一个Address类作为示例。然后,我们创建了一个ObjectConverter类,其中包含了ConvertToObject方法,该方法接受一个属性路径列表和一个属性值列表,并将其转换为指定类型的类对象。

ConvertToObject方法中,我们使用了反射来获取和设置类对象的属性。首先,我们根据属性路径中的第一个属性名获取对应的PropertyInfo对象,然后根据属性路径的长度判断是否还有嵌套属性。如果有嵌套属性,则递归调用SetProperty方法来处理嵌套属性。如果没有嵌套属性,则根据属性值的类型将属性值设置到类对象的对应属性上。

Main方法中,我们创建了一个属性路径列表和属性值列表作为示例数据,并调用ConvertToObject方法来将其转换为MyClass对象。然后,我们输出了转换后的对象的属性值。

这个功能适用于需要根据动态数据创建类对象的场景,例如解析JSON或XML数据并将其映射到类对象中。

推荐的腾讯云相关产品:无

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

相关·内容

没有搜到相关的视频

领券