如何将平面虚线列表属性转换为构造对象?

时间:2013-10-17 16:15:28

标签: c# dynamic reflection recursion

我有一个属性列表及其值,它们的格式为Dictionary<string, object>,如下所示:

Person.Name = "John Doe"
Person.Age = 27
Person.Address.House = "123"
Person.Address.Street = "Fake Street"
Person.Address.City = "Nowhere"
Person.Address.State = "NH"

有两个班级。 Person由字符串Name和原始Age以及包含AddressHouse,{{1}的复杂Street类组成}和City字符串属性。

基本上我想要做的是在当前程序集中查找类State并创建它的实例并分配所有值,无论类有多复杂,只要在最深处它们由基元,字符串和一些常见结构组成,例如Person

我有一个解决方案,允许我将顶级属性分配到其中一个复杂属性中。我假设我必须使用递归来解决这个问题,但我宁愿不这样做。

尽管如此,即使使用递归,我仍然不知道如何进入每个属性并分配它们的值。

在下面的这个例子中,我试图根据方法的参数将点线表示转换为类。我根据参数的类型查找相应的虚线表示,尝试查找匹配项。 DateTime基本上是DotField,其中键是KeyValuePair<string, object>属性。下面的代码可能无法正常工作,但它应该足够好地表达这个想法。

Name

3 个答案:

答案 0 :(得分:2)

您的Dictionary听起来与JSON格式的数据类似。如果您首先将其转换为兼容表单,则可以使用Json.Net将字典转换为对象。这是一个例子:

public static void Main()
{
    var dict = new Dictionary<string, object>
    {
        {"Person.Name", "John Doe"},
        {"Person.Age", 27},
        {"Person.Address.House", "123"},
        {"Person.Address.Street", "Fake Street"},
        {"Person.Address.City", "Nowhere"},
        {"Person.Address.State", "NH"},
    };
    var hierarchicalDict = GetItemAndChildren(dict, "Person");
    string json = JsonConvert.SerializeObject(hierarchicalDict);
    Person person = JsonConvert.DeserializeObject<Person>(json);
    // person has all of the values you'd expect
}
static object GetItemAndChildren(Dictionary<string, object> dict, string prefix = "")
{
    object val;
    if (dict.TryGetValue(prefix, out val))
        return val;
    else
    {
        if (!string.IsNullOrEmpty(prefix))
            prefix += ".";
        var children = new Dictionary<string, object>();
        foreach (var child in dict.Where(x => x.Key.StartsWith(prefix)).Select(x => x.Key.Substring(prefix.Length).Split(new[] { '.' }, 2)[0]).Distinct())
        {
            children[child] = GetItemAndChildren(dict, prefix + child);
        }
        return children;
    }
}

答案 1 :(得分:2)

你也可以使用反射来做到这一点。我很高兴写下这个:)

private object Eval(KeyValuePair<string, object> df)
{
    var properties = df.Key.Split('.');
    //line below just creates the root object (Person), you could replace it with whatever works in your example
    object root = Activator.CreateInstance(Assembly.GetExecutingAssembly().GetTypes().First(t => t.Name == properties.First()));

    var temp = root;

    for (int i = 1; i < properties.Length - 1; i++)
    {
        var propertyInfo = temp.GetType().GetProperty(properties[i]);
        var propertyInstance = Activator.CreateInstance(propertyInfo.PropertyType);                
        propertyInfo.SetValue(temp, propertyInstance, null);

        temp = propertyInstance;
    }

    temp.GetType().GetProperty(properties.Last()).SetValue(temp, df.Value, null);
    return root;
}

答案 2 :(得分:1)

这是我的完整代码示例。我决定远离疯狂的反射和映射,并从点列表结构中获取大量上下文信息。

我要感谢Timrla4提供的解决方案,并提供了解决此问题的信息。

    private static int GetPathDepth(string path)
    {
        int depth = 0;
        for (int i = 0; i < path.Length; i++)
        {
            if (path[i] == '.')
            {
                depth++;
            }
        }

        return depth;
    }

    private static string GetPathAtDepth(string path, int depth)
    {
        StringBuilder pathBuilder = new StringBuilder();

        string[] pathParts = path.Split('.');
        for (int i = 0; i < depth && i < pathParts.Length; i++)
        {
            string pathPart = pathParts[i];

            if (i == depth - 1 || i == pathParts.Length - 1)
            {
                pathBuilder.Append(pathPart);
            }
            else
            {
                pathBuilder.AppendFormat("{0}.", pathPart);
            }
        }

        string pathAtDepth = pathBuilder.ToString();
        return pathAtDepth;
    }

    private static string[] GetIntermediatePaths(string path)
    {
        int depth = GetPathDepth(path);

        string[] intermediatePaths = new string[depth];
        for (int i = 0; i < intermediatePaths.Length; i++)
        {
            string intermediatePath = GetPathAtDepth(path, i + 1);
            intermediatePaths[i] = intermediatePath;
        }

        return intermediatePaths;
    }

    private static PropertyInfo GetProperty(Type root, string path)
    {
        PropertyInfo result = null;

        string[] pathParts = path.Split('.');
        foreach (string pathPart in pathParts)
        {
            if (Object.ReferenceEquals(result, null))
            {
                result = root.GetProperty(pathPart);
            }
            else
            {
                result = result.PropertyType.GetProperty(pathPart);
            }
        }

        if (Object.ReferenceEquals(result, null))
        {
            throw new ArgumentException("A property at the specified path could not be located.", "path");
        }

        return result;
    }

    private static object GetParameter(ParameterInfo parameter, Dictionary<string, string> valueMap)
    {
        Type root = parameter.ParameterType;

        Dictionary<string, object> instanceMap = new Dictionary<string, object>();
        foreach (KeyValuePair<string, string> valueMapEntry in valueMap)
        {
            string path = valueMapEntry.Key;
            string value = valueMapEntry.Value;

            string[] intermediatePaths = GetIntermediatePaths(path);
            foreach (string intermediatePath in intermediatePaths)
            {
                PropertyInfo intermediateProperty = GetProperty(root, intermediatePath);

                object propertyTypeInstance;
                if (!instanceMap.TryGetValue(intermediatePath, out propertyTypeInstance))
                {
                    propertyTypeInstance = Activator.CreateInstance(intermediateProperty.PropertyType);
                    instanceMap.Add(intermediatePath, propertyTypeInstance);
                }
            }

            PropertyInfo property = GetProperty(root, path);

            TypeConverter converter = TypeDescriptor.GetConverter(property.PropertyType);
            object convertedValue = converter.ConvertFrom(value);

            instanceMap.Add(path, convertedValue);
        }

        object rootInstance = Activator.CreateInstance(root);

        foreach (KeyValuePair<string, object> instanceMapEntry in instanceMap)
        {
            string path = instanceMapEntry.Key;
            object value = instanceMapEntry.Value;

            PropertyInfo property = GetProperty(root, path);

            object instance;
            int depth = GetPathDepth(path);
            if (depth == 0)
            {
                instance = rootInstance;
            }
            else
            {
                string parentPath = GetPathAtDepth(path, depth);
                instance = instanceMap[parentPath];
            }

            property.SetValue(instance, value);
        }

        return rootInstance;
    }
相关问题