0

我正在尝试构建一个系统,将数据从垂直键值对存储系统转换为更传统的水平列存储。

源数据看起来像这样

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

4 回答 4

1

这是一些我认为可以为您提供一些帮助的代码。它不处理嵌套对象,但这里应该有足够的空间让您填补空白。

它使用您问题中的类,并填充一个地址对象。“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; }
}
}
于 2013-01-08T22:04:14.633 回答
0

使用 .NET Reflection 绑定目标类怎么样?我发现了一个样本,我相信它可以让你做你想做的事:

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

于 2013-01-08T20:38:21.473 回答
0

这似乎可行:

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 的 Activator 或 Assembly 进行一些更改。

注意:我从复数列表重命名为在末尾附加“列表”以保持一致性。

于 2013-01-09T15:40:33.260 回答
0

我可以提供的一条建议是使用 System.Convert.ChangeType(...) 方法在可能的情况下将值强制转换为目标类型,并在目标类型上查找静态 Parse(...) 方法,如果您' 从字符串值开始(如您上面的代码所示)。

于 2013-01-08T22:55:42.573 回答