1

I have a list of property paths and values as strings in a text file. Is there a mapping tool or serialize that could take a property path string( "Package.Customer.Name" ) and create the object and set the value?

4

1 回答 1

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可能会很好地工作,正如其他人已经建议的那样。

于 2012-06-12T20:50:54.240 回答