如何从字符串属性路径创建一个具有set属性的对象,如数据绑定呢?

时间:2012-06-12 20:22:28

标签: c# serialization mapping

我在文本文件中有一个属性路径和值列表作为字符串。是否有可以获取属性路径字符串(“Package.Customer.Name”)并创建对象并设置值的映射工具或序列化?

1 个答案:

答案 0 :(得分:0)

    /// <summary>
    /// With a data row, create an object and populate it with data
    /// </summary>
    private object CreateObject(List<DataCell> pRow, string objectName)
    {
        Type type = Type.GetType(objectName);
        if (type == null)
            throw new Exception(String.Format("Could not create type {0}", objectName));
        object obj = Activator.CreateInstance(type);

        foreach (DataCell cell in pRow)
        {           
            propagateToProperty(obj, *propertypath*, cell.CellValue);
        }

        return obj;
    }




   public static void propagateToProperty(object pObject, string pPropertyPath, object pValue)
        {
            Type t = pObject.GetType();
            object currentO = pObject;
            string[] path = pPropertyPath.Split('.');
            for (byte i = 0; i < path.Length; i++)
            {
                //go through object hierarchy
                PropertyInfo pi = t.GetProperty(path[i]);
                if (pi == null)
                    throw new Exception(String.Format("No property {0} on type {1}", path[i], pObject.GetType()));

                //an object in the property path
                if (i != path.Length - 1)
                {
                    t = pi.PropertyType;
                    object childObject = pi.GetValue(currentO, null);
                    if (childObject == null)
                    {
                        childObject = Activator.CreateInstance(t);
                        pi.SetValue(currentO, childObject, null);
                    }
                    currentO = childObject;

                //the target property
                else
                {
                    if (pi.PropertyType.IsEnum && pValue.GetType() != pi.PropertyType)
                        pValue = Enum.Parse(pi.PropertyType, pValue.ToString());
                    if (pi.PropertyType == typeof(Guid) && pValue.GetType() != pi.PropertyType)
                        pValue = new Guid(pValue.ToString());
                    if (pi.PropertyType == typeof(char))
                        if (pValue.ToString().Length == 0)
                            pValue = ' ';
                        else
                            pValue = pValue.ToString()[0];

                    pi.SetValue(currentO, pValue, null);
                }
            }
        }

这就是我用的东西。我只是在VS中打开它,也许它可以帮助你。 propertyPath 是您的属性路径的占位符,我从我的代码中删除了它。 如果您正在寻找更强大的解决方案,Automapper可能会很好地工作,正如其他人已经建议的那样。