如何像数据绑定一样从字符串属性路径创建具有 set 属性的对象

本文关键字:属性 创建 路径 对象 set 字符串 数据绑定 何像 一样 | 更新日期: 2023-09-27 18:36:53

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

如何像数据绑定一样从字符串属性路径创建具有 set 属性的对象

    /// <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中打开了它,也许它可以帮助您。属性路径是属性路径的占位符,我从我的代码中删除了它。如果您正在寻找更强大的解决方案,Automapper 可能会很好地工作,正如其他人已经建议的那样。