Динамическое сопоставление одного класса другому во время выполнения C#

Я пытаюсь создать систему, которая преобразует данные из системы хранения пар значений вертикальных ключей в более традиционное хранилище горизонтальных столбцов.

Исходные данные выглядят примерно так

public class Container
{
  public string Type { get; set; }
  public IEnumerable<Attribute> Attributes { get; set; }
  public IEnumerable<Container> RelatedContainers { get; set; }
}

public class Attributes
{
  public string Name{ get; set; }
  public string Value { get; set; }
}

Это будет генерировать данные что-то вроде

public class Person
{
  public string Name { get; set; }
  public IEnumerable<Address> Addresses { get; set; }
}


public class Address
{
  public string Line1 { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string Zip { get; set; }
}

В этой ситуации есть несколько ошибок. Прежде всего, я не знаю всех полей в целевых типах до времени выполнения. У меня есть грубое решение для этого и я могу генерировать новые классы во время выполнения на основе структуры исходных данных.

Хотя я не могу найти хороший способ сопоставить сами данные с новыми классами. Мне бы очень хотелось, чтобы мне указали на более простой способ решения проблемы, или помогу со следующим шагом на моем пути.

4 ответа

Вот некоторый код, который, я думаю, дает вам кое-что для начала. Он не обрабатывает вложенные объекты, но здесь должно быть достаточно для вас, чтобы заполнить пробелы.

Он использует классы из вашего вопроса и заполняет объект Address. Метод "CreateObjectFromContainer" является местом, где фактически выполняется работа.

using System;
using System.Collections.Generic;
using System.Linq;

namespace PopulateFromAttributes
{
class Program
{
    static void Main(string[] args)
    {
        // Set up some test data - an address in a Container
        var attributeData = new List<Attributes> 
        {
            new Attributes { Name = "Line1", Value = "123 Something Avenue" },
            new Attributes { Name = "City", Value = "Newville" },
            new Attributes { Name = "State", Value = "New York" },
            new Attributes { Name = "Zip", Value = "12345" },
        };
        Container container = new Container { Type = "Address", Attributes = attributeData };

        // Instantiate and Populate the object
        object populatedObject = CreateObjectFromContainer("PopulateFromAttributes", container);
        Address address = populatedObject as Address;

        // Output values
        Console.WriteLine(address.Line1);
        Console.WriteLine(address.City);
        Console.WriteLine(address.State);
        Console.WriteLine(address.Zip);
        Console.ReadKey();
    }

    /// <summary>
    /// Creates the object from container.
    /// </summary>
    /// <param name="objectNamespace">The namespace of the Type of the new object.</param>
    /// <param name="container">The container containing the object's data.</param>
    /// <returns>Returns a newly instantiated populated object.</returns>
    private static object CreateObjectFromContainer(string objectNamespace, Container container)
    {
        // Get the Type that we need to populate and instantiate an object of that type
        Type newType = Type.GetType(string.Format("{0}.{1}", objectNamespace, container.Type));
        object newObject = Activator.CreateInstance(newType);

        // Pass each attribute and populate the values
        var properties = newType.GetProperties();
        foreach (var property in properties)
        {
            var singleAttribute = container.Attributes.Where(a => a.Name == property.Name).FirstOrDefault();
            if (singleAttribute != null)
            {
                property.SetValue(newObject, singleAttribute.Value, null);
            }
        }

        return newObject;
    }
}

public class Container
{
    public string Type { get; set; }
    public IEnumerable<Attributes> Attributes { get; set; }
    public IEnumerable<Container> RelatedContainers { get; set; }
}

public class Attributes
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public class Address
{
    public string Line1 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}
}

Кажется, это может сработать:

object CreateObjectFromNVPair(Container c)
{
    Type t = Type.GetType(this.GetType().Namespace + "." + c.Type);
    object o = Activator.CreateInstance(t);
    if (c.Attributes != null)
    {
        foreach (Attribute a in c.Attributes)
        {
            PropertyInfo pi = o.GetType().GetProperty(a.Name);
            pi.SetValue(o, a.Value, null);
        }
    }
    if (c.RelatedContainers != null)
    {
        foreach (Container c2 in c.RelatedContainers)
        {
            Type lt = typeof(List<>);
            Type t2 = Type.GetType(this.GetType().Namespace + "." + c2.Type);
            PropertyInfo pi = o.GetType().GetProperty(c2.Type + "List");
            object l = pi.GetValue(o, null);
            if (l == null)
            {
                l = Activator.CreateInstance(lt.MakeGenericType(new Type[] { t2 }));
                pi.SetValue(o, l, null);
            }
            object o2 = CreateObjectFromNVPair(c2);
            MethodInfo mi = l.GetType().GetMethod("Add");
            mi.Invoke(l, new object[] { o2 });
        }
    }
    return o;
}

Некоторые изменения могут потребоваться для пространства имен и того, какой Активатор или Сборка используется для CreateInstance.

Примечание: я переименовал из списков множественного числа в добавление "Список" в конце для согласованности.

Один совет, который я могу предложить, - это использовать метод System.Convert.ChangeType (...) для приведения значений к типам назначения, где это возможно, и искать статический метод Parse (...) в типе назначения, если вы начинаем со строковых значений (как показывает ваш код выше).

Как насчет использования.NET Reflection для привязки вашего целевого класса? Я нашел один образец, который, как я верю, даст способ сделать то, что вы хотите:

http://www.codeproject.com/Articles/55710/Reflection-in-NET

Другие вопросы по тегам