C# 类型转换Dictionary转Model类

/// 
/// 把Model转换为DataRow
/// 
/// 
/// 
/// 
public static T ParseDictionaryToModel < T > (Dictionary < string, string > dict)
{
    //
    T obj =
        default(T);
    obj = Activator.CreateInstance < T > ();
    //根据Key值设定 Columns
    foreach(KeyValuePair < string, string > item in dict)
    {
        PropertyInfo prop = obj.GetType().GetProperty(item.Key);
        if(!string.IsNullOrEmpty(item.Value))
        {
            object value = item.Value;
            //Nullable 获取Model类字段的真实类型
            Type itemType = Nullable.GetUnderlyingType(prop.PropertyType) == null ? prop.PropertyType : Nullable.GetUnderlyingType(prop.PropertyType);
            //根据Model类字段的真实类型进行转换
            prop.SetValue(obj, Convert.ChangeType(value, itemType), null);
        }
    }
    return obj;
}

主要方法体

public static T DictionaryToModel(this Dictionary Dict, T NewModel)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using MyCmn;

namespace MyOql
{
    public static partial class dbo
    {
        /// 
        /// 把 Model 转为 字典,是一个和  ModelToDictionary(RuleBase Entity, IModel objModel) 相同算法的函数。
        /// 
        /// 功能和 FastInvoke 是一样的。针对 WhereClip 会有优化。
        /// 
        /// 
        public static StringDict ModelToStringDict(object objModel)
        {
            WhereClip where = objModel as WhereClip;
            if (where != null)
            {
                var dictModel = new StringDict();
                do
                {
                    if (dbo.EqualsNull(where.Query)) break;

                    dictModel[where.Query.ToString()] = where.Value.AsString(null);

                } while ((where = where.Next) != null);
                return dictModel;
            }

            return FastInvoke.Model2StringDict(objModel);
        }
        /// 
        /// 把 Model 转为 字典。核心函数。
        /// 
        /// 数据实体推入到数据库时使用,解析如下类型: 
        /// String
        /// Dictionary<ColumnClip, object>
        /// Dictionary<string, object>
        /// Dictionary<string, string>
        /// 类
        /// 值类型结构体
        /// 
        /// 
        /// 如果为空,则生成 ConstColumn 
        /// 
        /// 
        public static XmlDictionary<ColumnClip, object> ModelToDictionary(RuleBase Entity, IModel objModel)
        {
            XmlDictionary<ColumnClip, object> dictModel = objModel as XmlDictionary<ColumnClip, object>;
            if (dictModel != null)
            {
                return dictModel;
            }

            Func<string, ColumnClip> GetColumn = colKey =>
            {
                if (Entity == null) return new ConstColumn(colKey);
                var retVal = Entity.GetColumn(colKey);
                if (retVal.IsDBNull()) return new ConstColumn(colKey);
                else return retVal;
            };

            IDictionary dict = objModel as IDictionary;
            if (dict != null)
            {
                dictModel = new XmlDictionary<ColumnClip, object>();

                var objTypes = objModel.GetType().getGenericType().GetGenericArguments();

                //Key 可能是 string,Column 没其它的.
                if (objTypes[0] == typeof(string))
                {
                    foreach (string strKey in dict.Keys)
                    {
                        var theCol = GetColumn(strKey);
                        if (dbo.EqualsNull(theCol) == false)
                        {
                            dictModel.Add(theCol, dict[strKey]);
                        }

                    }
                    return dictModel;
                }
                else if (objTypes[0] == typeof(ColumnClip))
                {
                    foreach (ColumnClip colKey in dict.Keys)
                    {
                        dictModel.Add(colKey, dict[colKey]);
                    }
                    return dictModel;
                }

            }

            WhereClip where = objModel as WhereClip;
            if (where != null)
            {
                dictModel = new XmlDictionary<ColumnClip, object>();
                do
                {
                    if (dbo.EqualsNull(where.Query)) break;

                    dictModel[where.Query] = where.Value;

                } while ((where = where.Next) != null);
                return dictModel;
            }

            dictModel = new XmlDictionary<ColumnClip, object>();

            IEntity entity = objModel as IEntity;
            if (entity != null)
            {
                foreach (var strKey in entity.GetProperties())
                {
                    var theCol = GetColumn(strKey);
                    if (theCol.EqualsNull()) continue;
                    dictModel.Add(theCol, entity.GetPropertyValue(strKey));
                }
                return dictModel;
            }


            GodError.Check((objModel as ContextClipBase) != null, "Model 不能是 MyOql 子句");


            Type type = objModel.GetType();
            GodError.Check(type.FullName == "MyOql.ColumnClip", "ColumnClip 不能作为 Model");
            foreach (PropertyInfo prop in type.GetProperties())
            {
                var methodInfo = type.GetMethod("get_" + prop.Name);
                if (methodInfo == null) continue;

                var theCol = GetColumn(prop.Name);
                dictModel.Add(theCol, FastInvoke.GetPropertyValue(objModel, type, methodInfo));
            }

            return dictModel;
        }


        / 
        / 将一个对象转化为 XmlDictionary
        / 
        / 
        / 
        / 
        //public static XmlDictionary ModelToDictionary(T objModel)
        //    where T : class , new()
        //{
        //    Type type = typeof(T);
        //    var IsDict = type.GetInterface("System.Collections.IDictionary") != null;
        //    XmlDictionary dict = new XmlDictionary();

        //    if (IsDict == false)
        //    {
        //        var entity = objModel as IEntity;
        //        if (entity != null)
        //        {
        //            foreach (var key in entity.GetProperties())
        //            {
        //                dict[key] = entity.GetPropertyValue(key);
        //            }
        //        }
        //        else
        //        {
        //            foreach (var pi in type.GetProperties())
        //            {
        //                var methodInfo = type.GetMethod("get_" + pi.Name);
        //                if (methodInfo == null) continue;

        //                dict[pi.Name] = FastInvoke.GetPropertyValue(objModel, type, methodInfo);
        //            }
        //        }
        //    }
        //    else
        //    {
        //        var objDict = objModel as IDictionary;

        //        foreach (var key in objDict.Keys)
        //        {
        //            dict[key.AsString()] = objDict[key];
        //        }
        //    }

        //    return dict;
        //}

        public static T DictionaryToModel<TKey, TValue, T>(this Dictionary<TKey, TValue> Dict, T NewModel)
        {
            return DictionaryToFuncModel<TKey, TValue, T>(Dict, () => NewModel);
        }

        /// 
        /// 把字典解析到 Model 类型的 Model 上。
        /// 
        ///  逻辑同 FastInvoke.StringDictToModel
        /// 从数据库返回数据实体时使用,解析如下类型: 
        /// String
        /// IDictionary
        /// 类(支持递归赋值。如果第一级属性找不到,则查找第二级非基元属性,依次向下查找。)
        /// Json树格式,如果在HTML中Post Json对象,如 cols[id][sid] = 10 则可以映射到合适的对象上。
        /// 值类型结构体,主要适用于 数值,Enum类型。对于结构体,把 结果集第一项值 强制类型转换为该结构体类型,所以尽量避免使用自定义结构体。
        /// 
        /// 
        /// 
        /// 
        /// 关键是 泛型!Model可以为null
        /// 
        public static T DictionaryToFuncModel<TKey, TValue, T>(this IDictionary<TKey, TValue> Dict, Func<T> NewModelFunc)
        {
            if (Dict == null)
            {
                return default(T);
            }

            Type type = typeof(T);

            T ret = default(T);

            //Object 表示没有反射出 T 类型,  IsInterface 时亦然。
            if (type.FullName == "System.Object" || type.IsInterface)
            {
                ret = NewModelFunc();
                type = ret.GetType();
            }

            var retDict = ret as IDictionary;

            if (retDict != null)
            {
                var genericTypes = type.getGenericType().GetGenericArguments();
                if (genericTypes.Length == 2)
                {
                    Func<Type, object, object> getKey = (_type, _value) =>
                    {
                        if (_type.FullName == "MyOql.ColumnClip")
                        {
                            return new ConstColumn(_value);
                        }
                        return ValueProc.AsType(_type, _value);
                    };

                    foreach (KeyValuePair<TKey, TValue> kv in Dict)
                    {
                        retDict[getKey(genericTypes[0], kv.Key)] = ValueProc.AsType(genericTypes[1], kv.Value);
                    }

                }
                else
                {
                    foreach (var kv in Dict)
                    {
                        retDict[kv.Key] = kv.Value;
                    }
                }
                return (T)(object)retDict;
            }

            return FastInvoke.StringDict2Model(StringDict.LoadFrom(Dict), NewModelFunc);
        }

        /// 
        /// 设置字典的属性。
        /// 
        /// 数据源。如果该数据源没有相应字典,则会自动创建
        /// Html Post 的Key,如:  cols[id][sid] 
        /// 
        private static void setDictValue(XmlDictionary<string, object> dict, string key, object value)
        {
            var allDeep = key.Count(c => c == '[');

            var curKey_LastIndex = 0;
            var curKey = string.Empty;
            //取当前级别的Object
            XmlDictionary<string, object> curObject = dict;
            for (int i = 0; i < allDeep; i++)
            {
                curKey_LastIndex = key.IndexOf('[', curKey_LastIndex + 1);

                //计算当前深度下的Key  , 如:cols[cid][sid],深度为0 , 返回 cid ,为1返回 sid
                curKey = key.Slice(curKey_LastIndex + 1, key.IndexOf(']', curKey_LastIndex + 1)).AsString();

                if (i < (allDeep - 1))
                {
                    if (curObject.ContainsKey(curKey) == false) curObject[curKey] = new XmlDictionary<string, object>();
                    curObject = curObject[curKey] as XmlDictionary<string, object>;
                }
            }
            curObject[curKey] = value;
        }


        /// 
        /// 更新Model的一个属性值。Model可以是 字典,Where,类.
        /// 
        /// 可以是 字典,Where,类.
        /// 要更新的属性
        /// 要更新的值
        /// 
        public static bool UpdateOneProperty(object objModel, ColumnClip Column, object Value)
        {
            if (Column.IsDBNull()) return false;
            Type type = objModel.GetType();
            IDictionary dictModel = objModel as IDictionary;
            if (dictModel != null)
            {
                var objTypes = type.getGenericType().GetGenericArguments();

                //Key 可能是 string,Column 没其它的.
                if (objTypes[0] == typeof(string))
                {
                    foreach (string strKey in dictModel.Keys)
                    {
                        if (Column.NameEquals(strKey, true))
                        {
                            dictModel[strKey] = ValueProc.AsType(objTypes[1], Value);
                            return true;
                        }
                    }
                    dictModel[Column.Name] = ValueProc.AsType(objTypes[1], Value);
                    return true;
                }
                else if (objTypes[0] == typeof(ColumnClip))
                {
                    foreach (ColumnClip colKey in dictModel.Keys)
                    {
                        if (Column.NameEquals(colKey))
                        {
                            dictModel[colKey] = ValueProc.AsType(objTypes[1], Value);
                            return true;
                        }
                    }
                    dictModel[Column] = ValueProc.AsType(objTypes[1], Value);
                    return true;
                }
            }


            WhereClip whereModel = objModel as WhereClip;

            if (whereModel != null)
            {

                var curWhere = whereModel;
                while (curWhere.IsNull() == false && dbo.EqualsNull(curWhere.Query) == false)
                {
                    if (curWhere.Query.NameEquals(Column.Name, true))
                    {
                        curWhere.Value = Value;
                        return true;
                    }


                    if (curWhere.Next.IsNull())
                    {
                        break;
                    }
                    else curWhere = curWhere.Next;
                }

                if (curWhere.IsNull())
                {
                    curWhere = curWhere.Next = new WhereClip();
                }
                curWhere.Linker = SqlOperator.And;
                curWhere.Query = Column;
                curWhere.Operator = SqlOperator.Equal;
                curWhere.Value = Value;
                return true;
            }

            dictModel = new XmlDictionary<string, object>();

            var entity = objModel as IEntity;
            if (entity != null)
            {
                entity.SetPropertyValue(Column.Name, Value);
            }
            else
            {
                FastInvoke.SetPropertyValue(objModel, type, type.GetMethod("set_" + Column.Name), Value);
            }
            //foreach (PropertyInfo item in type.GetProperties())
            //{
            //    if (item.Name == Column.Name)
            //    {
            //        FastInvoke.SetPropertyValue(objModel, Column.Name, Value);
            //        return true;
            //    }
            //}
            return false;
        }


        /// 
        /// Reader 转为 字典 函数,核心函数。
        /// 
        /// 
        /// 
        public static RowData ToDictionary(this DbDataReader openReader)
        {
            var dict = new RowData();

            for (int i = 0; i < openReader.FieldCount; i++)
            {
                if (openReader.GetName(i).StartsWith("__IgNoRe__")) continue;
                dict[openReader.GetName(i)] = openReader.GetValue(i);
            }
            return dict;
        }

        /// 
        /// DataRow 转为 字典 函数,核心函数。
        /// 
        /// 
        /// 
        public static XmlDictionary<string, object> ToDictionary(this DataRow row)
        {
            XmlDictionary<string, object> dict = new XmlDictionary<string, object>();
            for (int i = 0; i < row.Table.Columns.Count; i++)
            {
                if (row.Table.Columns[i].ColumnName.StartsWith("__IgNoRe__")) continue;
                dict[row.Table.Columns[i].ColumnName] = row[i];
            }
            return dict;
        }


        public static object[] ToValueData(this DbDataReader openReader)
        {
            return ToValueData(openReader, null);
        }

        public static object[] ToValueData(this DbDataReader openReader, params string[] Columns)
        {
            if (Columns == null || Columns.Length == 0)
            {

                List<object> list = new List<object>();
                //如果第一列为行号。则忽略掉一列。

                for (int i = 0; i < openReader.VisibleFieldCount; i++)
                {
                    if (openReader.GetName(i).StartsWith("__IgNoRe__"))
                    {
                        continue;
                    }

                    list.Add(openReader.GetValue(i));
                }
                return list.ToArray();
            }
            else
            {
                List<object> list = new List<object>();
                foreach (var col in Columns)
                {
                    list.Add(openReader.GetValue(openReader.GetOrdinal(col)));
                }
                return list.ToArray();
            }
        }

        /// 
        /// 把 DataTable 转为实体列表。由于DataTable 是一次装载,不对 DataRow 应用权限控制机制
        /// 
        /// 
        /// 
        /// 
        public static List<T> ToEntityList<T>(this DataTable table, Func<T> NewModelFunc)
        {
            List<T> list = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                list.Add(ToEntity(row, NewModelFunc));
            }
            return list;
        }


        //public static List ToEntityList(this SelecteClip select )
        //    where T:RuleBase
        //    where TModel:struct
        //{
        //    return select.ToEntityList(() => new TModel());
        //}

        /// 
        /// 把 DataTable 转为实体列表。转换过程不应用权限过滤机制.
        /// 
        /// 
        /// 
        /// 
        public static List<T> ToEntityList<T>(this DataTable table) where T : new()
        {
            List<T> list = new List<T>();
            foreach (DataRow row in table.Rows)
            {
                list.Add(ToEntity<T>(row));
            }
            return list;
        }

        /// 
        /// 把 DataReader 转为实体。
        /// 
        /// 
        /// 
        /// 
        public static T ToEntity<T>(this DbDataReader openReader) where T : new()
        {
            return ToEntity(openReader, () => new T());
        }

        public static T ToEntity<T>(this DbDataReader openReader, T Model) where T : new()
        {
            return ToEntity(openReader, () => new T());
        }

        / 
        / Reader 转为 字典 函数,核心函数之一。用权限过滤。
        / 
        / 
        / 
        //public static XmlDictionary ToDictionary(this DbDataReader openReader)
        //{
        //    return ToDictionary(openReader, true);
        //}

        /// 
        /// 启用权限的写法。如果不启用权限请用 DictionaryToModel(ToDictionary(openReader,false), Model)
        /// 
        /// 
        /// 
        /// 
        /// 
        public static T ToEntity<T>(this DbDataReader openReader, Func<T> NewModelFunc)
        {
            return DictionaryToFuncModel(ToDictionary(openReader), NewModelFunc);
        }


        /// 
        /// 把 DataRow 转为实体。由于DataTable 是一次装载,不对 DataRow 应用权限控制机制
        /// 
        /// 
        /// 
        /// 
        public static T ToEntity<T>(this DataRow row) where T : new()
        {
            return (T)ToEntity(row, () => new T());
        }

        /// 
        /// 把 DataRow 转为实体。由于DataTable 是一次装载,不对 DataRow 应用权限控制机制
        /// 
        /// 
        /// 
        /// 生成默认Model构造器的回调.
        /// 
        public static T ToEntity<T>(this DataRow row, Func<T> NewModelFunc)
        {
            return DictionaryToFuncModel(ToDictionary(row), NewModelFunc);
        }

        public static string ToEntity(this DataRow row, string DefaultValue)
        {
            return DictionaryToFuncModel(ToDictionary(row), () => DefaultValue);
        }
        /// 
        /// 把 DbName 转换为 程序 所使用的名称.
        /// 
        /// 
        /// 如果数据库名称中出现以下 指定的分隔字符 , 则按以下分隔字符 进行分隔, 并把每个部分首字母大写之后进行联接. 分隔字符有:
        /// 1.空格
        /// 2.下划线 _
        /// 3.加号 +
        /// 4.减号 -
        /// 5.#
        /// 6.&
        /// 7.竖线 |
        /// 8.冒号 :
        /// 9.分号 ;
        /// 10.小于号 <
        /// 11.大于号 >
        /// 12.逗号 , 
        /// 13.点号 .
        /// 14.$
        /// 15.左括号
        /// 16.右括号
        /// 
        /// 如果没有出现上述分隔符, 如果数据库名称 全大写,或全小写, 则按首字母大写转换, 否则 返回数据库名称.
        /// 
        /// 
        /// 
        public static string TranslateDbName(string DbName)
        {
            if (MyOqlConfigScope.Config != null && MyOqlConfigScope.Config.IsValueCreated && MyOqlConfigScope.Config.Value.Contains(ReConfigEnum.NoEscapeDbName)) return DbName;

            if (DbName.HasValue() == false) return DbName;

            //在Sqlserver中,列名可以以 # 开头,MyOql规定,以#开头的列名,不转义。
            if (DbName.StartsWith("#")) return DbName.Substring(1);

            var ents = DbName.Split(" _+-&|:;<>,.$(){}".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);


            Func<string, string> Format = o =>
            {
                if (o.HasValue() == false) return string.Empty;
                else if (o.Length == 1) return o.ToUpperInvariant();
                else if (o.IsSameCase()) return o.First().ToString().ToUpperInvariant() + o.Substring(1).ToLower();
                else return o.First().ToString().ToUpperInvariant() + o.Substring(1);
            };

            return string.Join("", ents.Select(o => Format(o)).ToArray());

        }

        /// 
        /// 把一个 DataTable 转换为 MyOqlSet
        /// 
        /// 
        /// 
        /// 
        /// 
        public static MyOqlSet ToMyOqlSet<T>(this DataTable dataTable, T Rule)
            where T : RuleBase
        {
            return new MyOqlSet(Rule).Load(dataTable);
        }


        public static MyOqlSet ToMyOqlSet<T>(this List<XmlDictionary<string, object>> dictList, T Rule)
            where T : RuleBase
        {
            return new MyOqlSet(Rule).Load(dictList);
        }
    }
}

主要方法体

public T DictionaryToModel(T t, Dictionary dic)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Web;
using LogHelper;
using System.ComponentModel;
using Microsoft.VisualBasic;
using gfVehicleLibraryAJ;

namespace ConvertInfo
{
    public class ModelReflection
    {
        public struct NameAndValue
        {
            public string Name;
            public string Value;
        }

        public PropertyInfo[] GetPropertyInfos(Type type)
        {
            return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }

        /// 
        /// 得到子类中所有属性
        /// 
        /// 
        /// 
        /// 
        public void GetClassName<T>(T t, ref List<PropertyInfo> lstParent, ref List<PropertyInfo> lstChildren, bool bFindGrandpa = false)
        {
            PropertyInfo[] pIs = GetPropertyInfos(t.GetType());
            PropertyInfo[] pps;
            if (!bFindGrandpa)
            {
                pps = GetPropertyInfos(t.GetType().BaseType);
            }
            else
            {
                pps = GetPropertyInfos(t.GetType().BaseType.BaseType);
            }

            List<PropertyInfo> lstPIs = pIs.ToList();
            List<PropertyInfo> lstPps = pps.ToList();

            foreach (var v in pIs)
            {
                bool b = false;
                foreach (var j in pps)
                {
                    if (v.Name == j.Name)
                    {
                        b = true;
                        break;
                    }
                }

                if (b)
                {
                    lstParent.Add(v);
                }

                if (!b)
                {
                    lstChildren.Add(v);
                }
            }
        }

        #region AJ Para
        /// 
        /// 设置model值
        /// 
        /// 
        /// 
        /// 
        /// 
        public T ParaSetModelValue<T>(T t, string strType, string strContent)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strContent);

                PropertyInfo[] pps = GetPropertyInfos(t.GetType());
                Type target = t.GetType();

                XmlNode xn = doc.SelectSingleNode("//" + strType);

                XmlNodeList nodes = xn.ChildNodes;
                if (nodes.Count > 0)
                {
                    List<string> lstError = new List<string>();
                    foreach (XmlNode v in nodes)
                    {
                        try
                        {
                            PropertyInfo targetPP = target.GetProperty(v.Name);
                            object objValue = v.InnerText;
                            if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                            {
                                targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                            }
                        }
                        catch (Exception ee)
                        {
                            lstError.Add(" 项目:[" + v.Name + "], 值:[" + v.InnerText + "]转换失败.");
                            continue;
                        }
                    }

                    #region 日志记录
                    string strCategory = Log.LogType.NetUpDown.ToString();
                    LOG_INFO logInfo = new LOG_INFO();
                    logInfo.Category = strCategory;
                    logInfo.HostName = System.Net.Dns.GetHostName();
                    logInfo.IPAddress = Log.GetIPAddress(logInfo.HostName);
                    logInfo.LogTime = DateTime.Now;
                    logInfo.FS_Infor = strContent;
                    logInfo.JS_Infor = "";
                    logInfo.Log_Infor = "2." + t.GetType().Name.ToString() + "xml转换成Model成功.";
                    string strErrorPart = "";
                    foreach (var v in lstError)
                    {
                        strErrorPart += v + ",";
                    }
                    if (string.IsNullOrEmpty(strErrorPart) == false)
                    {
                        logInfo.Log_Infor = logInfo.Log_Infor + "部分转换失败,失败参数为:" + strErrorPart;
                    }
                    
                    logInfo.Name = "上传下载";
                    logInfo.FunName = "ModelReflection.cs -> ParaSetModelValue";

                    Log.WriteLog(logInfo);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                #region 日志记录
                string strCategory = Log.LogType.NPFail.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = System.Net.Dns.GetHostName();
                logInfo.IPAddress = Log.GetIPAddress(logInfo.HostName);
                logInfo.LogTime = DateTime.Now;
                logInfo.FS_Infor = strContent;
                logInfo.JS_Infor = "";
                logInfo.Log_Infor = "2." + t.GetType().Name.ToString() + "xml转换成Model失败,失败原因为:" + HttpUtility.UrlEncode(ex.Message);

                logInfo.Name = "联网失败";
                logInfo.FunName = "ModelReflection.cs -> ParaSetModelValue";

                Log.WriteLog(logInfo);
                #endregion
            }
            return t;
        }

        /// 
        /// 设置model值,仅适用与18C62
        /// 
        /// 
        /// 
        /// 
        /// 
        public Vehicle_18C62_Para ParaSetModelValue_18C62(Vehicle_18C62_Para m_Para, string strType, string strContent)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strContent);

                PropertyInfo[] pps = GetPropertyInfos(m_Para.GetType());
                Type target = m_Para.GetType();

                XmlNode xn = doc.SelectSingleNode("//" + strType);

                XmlNodeList nodes = xn.ChildNodes;
                if (nodes.Count > 0)
                {
                    List<string> lstError = new List<string>();
                    foreach (XmlNode v in nodes)
                    {
                        try
                        {
                            if (v.Name == "rgjyjgs" || v.Name == "yqsbjyjgs")
                            {
                                ParaSetModelValue_18C62_Sub(ref m_Para, xn, v.Name);
                            }

                            PropertyInfo targetPP = target.GetProperty(v.Name);
                            object objValue = v.InnerText;
                            if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                            {
                                targetPP.SetValue(m_Para, SD_ChanageType(objValue, targetPP.PropertyType), null);
                            }
                        }
                        catch (Exception ee)
                        {
                            lstError.Add(" 项目:[" + v.Name + "], 值:[" + v.InnerText + "]转换失败.");
                            continue;
                        }
                    }

                    #region 日志记录
                    string strCategory = Log.LogType.NetUpDown.ToString();
                    LOG_INFO logInfo = new LOG_INFO();
                    logInfo.Category = strCategory;
                    logInfo.HostName = System.Net.Dns.GetHostName();
                    logInfo.IPAddress = Log.GetIPAddress(logInfo.HostName);
                    logInfo.LogTime = DateTime.Now;
                    logInfo.FS_Infor = strContent;
                    logInfo.JS_Infor = "";
                    logInfo.Log_Infor = m_Para.GetType().Name.ToString();
                    foreach (var v in lstError)
                    {
                        logInfo.Log_Infor = logInfo.Log_Infor + v;
                    }

                    logInfo.Name = "上传下载";
                    logInfo.FunName = "ModelReflection.cs -> ParaSetModelValue";

                    Log.WriteLog(logInfo);
                    #endregion
                }
            }
            catch (Exception ex)
            {
            }
            return m_Para;
        }

        /// 
        /// 得到18C62子项值
        /// 
        /// 
        /// 
        /// 
        private void ParaSetModelValue_18C62_Sub(ref Vehicle_18C62_Para m_Para, XmlNode node, string nodeName)
        {
            dynamic m_None = new Vehicle_18C62_RG_Para();
            Vehicle_18C62_YQ_Para m_YQ = new Vehicle_18C62_YQ_Para();
            if (nodeName.ToLower() == "rgjyjgs")
            {
                m_Para.RG = new List<Vehicle_18C62_RG_Para>();
            }

            if (nodeName.ToLower() == "yqsbjyjgs")
            {
                m_Para.YQ = new List<Vehicle_18C62_YQ_Para>();
            }

            XmlNode xn = node.SelectSingleNode(nodeName);
            if (xn.HasChildNodes)
            {
                XmlNodeList nodes = xn.ChildNodes;
                if (nodes != null && nodes.Count > 0)
                {
                    foreach (XmlNode vList in nodes)
                    {
                        if (vList.HasChildNodes)
                        {
                            var vSubChildRen = vList.ChildNodes;
                            if (nodeName.ToLower() == "yqsbjyjgs")
                            {
                                m_None = new Vehicle_18C62_YQ_Para();
                            }

                            if (nodeName.ToLower() == "rgjyjgs")
                            {
                                m_None = new Vehicle_18C62_RG_Para();
                            }
                            
                            foreach (XmlNode v in vSubChildRen)
                            {
                                Type target = m_None.GetType();
                                if (v.HasChildNodes)
                                {
                                    PropertyInfo targetPP = target.GetProperty(v.Name);
                                    object objValue = v.InnerText;
                                    if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                                    {
                                        targetPP.SetValue(m_None, SD_ChanageType(objValue, targetPP.PropertyType), null);
                                    }
                                }
                            }

                            if (m_None is Vehicle_18C62_RG_Para)
                            {
                                m_Para.RG.Add(m_None);
                            }

                            if (m_None is Vehicle_18C62_YQ_Para)
                            {
                                m_Para.YQ.Add(m_None);
                            }
                        }
                    }
                }
            }
        }

        /// 
        /// 参数实体转换成XML
        /// 
        /// 
        /// 
        /// 
        /// 
        public string ParaModelToXML<T>(T t, string strType)
        {
            string strRet = "";
            try
            {
                strRet = "";
                strRet += "";
                strRet += "<" + strType + ">";

                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();
                GetClassName(t, ref lstParent, ref lstChildren);

                foreach (var v in lstChildren)
                {
                    object objValue = v.GetValue(t, null);
                    if (objValue == null || string.IsNullOrEmpty(objValue.ToString()))
                    {
                        strRet += "<" + v.Name + "> + v.Name + ">";
                    }
                    else
                    {
                        //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                        DateTime dateTemp;
                        string strValue;
                        if (IsDateTime(objValue.ToString()))
                        {
                            dateTemp = Convert.ToDateTime(objValue.ToString());
                            strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        else
                        {
                            strValue = objValue.ToString();
                        }

#if RZLD
                        //日照兰大这边,18C58多个开始时间,发送给联网公司时,去掉kssj
                        if (typeof(T).Name == "Vehicle_18C58_Para" && v.Name == "kssj")
                        {
                            continue;
                        }
#endif
                        if (typeof(T).Name == "Vehicle_18C52_Para" && v.Name == "jclsh")
                        {
                            continue;
                        }

                        if (typeof(T).Name == "Vehicle_18C66_Para" && v.Name == "jclsh")
                        {
                            continue;
                        }

                        strRet += "<" + v.Name + ">" + strValue + " + v.Name + ">";
                    }
                }

                strRet += " + strType + ">";
                strRet += "";

                #region 日志记录
                string strCategory = Log.LogType.NetUpDown.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = System.Net.Dns.GetHostName();
                logInfo.IPAddress = Log.GetIPAddress(logInfo.HostName);
                logInfo.LogTime = DateTime.Now;
                logInfo.FS_Infor = strRet;
                logInfo.JS_Infor = "";
                logInfo.Log_Infor = "3. 18C82 将Model转换成XML成功";
                logInfo.Name = "上传下载";
                logInfo.FunName = "ModelReflection.cs -> ParaModelToXML()";

                Log.WriteLog(logInfo);
                #endregion
            }
            catch (Exception ex)
            {
                #region 日志记录
                string strCategory = Log.LogType.NPFail.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = System.Net.Dns.GetHostName();
                logInfo.IPAddress = Log.GetIPAddress(logInfo.HostName);
                logInfo.LogTime = DateTime.Now;
                logInfo.FS_Infor = strRet;
                logInfo.JS_Infor = "";
                logInfo.Log_Infor = "3. 18C82 将Model转换成XML失败,失败原因:" + HttpUtility.UrlEncode(ex.Message);
                logInfo.Name = "转换失败";
                logInfo.FunName = "ModelReflection.cs -> ParaModelToXML()";

                Log.WriteLog(logInfo);
                #endregion
            }
            return strRet;
        }

        /// 
        /// 仅适用与18C81,两重基类
        /// 
        /// 
        /// 
        /// 
        /// 
        public string ParaModelToXML_Ex<T>(T t, string strType)
        {
            string strRet = "";
            try
            {
                strRet = "";
                strRet += "";
                strRet += "<" + strType + ">";

                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();
                GetClassName(t, ref lstParent, ref lstChildren, true);

                foreach (var v in lstChildren)
                {
                    object objValue = v.GetValue(t, null);
                    if (objValue == null || string.IsNullOrEmpty(objValue.ToString()))
                    {
                        strRet += "<" + v.Name + "> + v.Name + ">";
                    }
                    else
                    {
                        //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                        DateTime dateTemp;
                        string strValue;
                        if (IsDateTime(objValue.ToString()))
                        {
                            dateTemp = Convert.ToDateTime(objValue.ToString());
                            strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        else
                        {
                            strValue = objValue.ToString();
                        }

                        strRet += "<" + v.Name + ">" + strValue + " + v.Name + ">";
                    }
                }

                strRet += " + strType + ">";
                strRet += "";
            }
            catch (Exception ex)
            {

            }
            return strRet;
        }

        /// 
        /// 仅适用与18C62,两重基类
        /// 
        /// 
        /// 
        /// 
        /// 
        public string ParaModelToXML_18C62(Vehicle_18C62_Para m_18C62, string strType)
        {
            string strRet = "";
            try
            {
                strRet = "";
                strRet += "";
                strRet += "<" + strType + ">";

                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();
                GetClassName(m_18C62, ref lstParent, ref lstChildren);

                foreach (var v in lstChildren)
                {
                    if (v.Name == "RG" || v.Name == "YQ")
                    {
                        continue;
                    }
                     
                    object objValue = v.GetValue(m_18C62, null);
                    if (objValue == null || string.IsNullOrEmpty(objValue.ToString()))
                    {
                        strRet += "<" + v.Name + "> + v.Name + ">";
                    }
                    else
                    {
                        //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                        DateTime dateTemp;
                        string strValue;
                        if (IsDateTime(objValue.ToString()))
                        {
                            dateTemp = Convert.ToDateTime(objValue.ToString());
                            strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        else
                        {
                            strValue = objValue.ToString();
                        }
                        strRet += "<" + v.Name + ">" + strValue + " + v.Name + ">";
                    }
                }

                #region 人工
                List<PropertyInfo> lstParent_RG = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren_RG = new List<PropertyInfo>();
                strRet += "";
                for (int i = 0; i < m_18C62.RG.Count; i++)
                {
                    if (i == 0)
                    {
                        GetClassName(m_18C62.RG[0], ref lstParent_RG, ref lstChildren_RG);
                    }
                    strRet += "";

                    foreach (var v in lstChildren_RG)
                    {
                        object objValue = v.GetValue(m_18C62.RG[i], null);
                        if (objValue == null || string.IsNullOrEmpty(objValue.ToString()))
                        {
                            strRet += "<" + v.Name + "> + v.Name + ">";
                        }
                        else
                        {
                            //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                            DateTime dateTemp;
                            string strValue;
                            if (IsDateTime(objValue.ToString()))
                            {
                                dateTemp = Convert.ToDateTime(objValue.ToString());
                                strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            else
                            {
                                strValue = objValue.ToString();
                            }
                            strRet += "<" + v.Name + ">" + strValue + " + v.Name + ">";
                        }
                    }

                    strRet += "";
                }
                strRet += "";
                #endregion

                #region 仪器
                List<PropertyInfo> lstParent_YQ = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren_YQ = new List<PropertyInfo>();
                strRet += "";
                for (int i = 0; i < m_18C62.YQ.Count; i++)
                {
                    if (i == 0)
                    {
                        GetClassName(m_18C62.YQ[0], ref lstParent_YQ, ref lstChildren_YQ);
                    }
                    strRet += "";

                    foreach (var v in lstChildren_YQ)
                    {
                        object objValue = v.GetValue(m_18C62.YQ[i], null);
                        if (objValue == null || string.IsNullOrEmpty(objValue.ToString()))
                        {
                            strRet += "<" + v.Name + "> + v.Name + ">";
                        }
                        else
                        {
                            //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                            DateTime dateTemp;
                            string strValue;
                            if (IsDateTime(objValue.ToString()))
                            {
                                dateTemp = Convert.ToDateTime(objValue.ToString());
                                strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            else
                            {
                                strValue = objValue.ToString();
                            }
                            strRet += "<" + v.Name + ">" + strValue + " + v.Name + ">";
                        }
                    }

                    strRet += "";
                }
                strRet += "";
                #endregion

                strRet += " + strType + ">";
                strRet += "";
            }
            catch (Exception ex)
            {

            }
            return strRet;
        }
        #endregion

        /// 
        /// 是否是带时间的日期格式
        /// 
        /// 
        /// 
        private bool IsDateTime(string strValue)
        {
            bool bDate = false;
            if (Information.IsDate(strValue) && (strValue.ToString().Contains("-") || strValue.ToString().Contains("/")) && strValue.ToString().Length > 11)
                bDate = true;
            return bDate;
        }

        #region AJ Result
        public T ResultSetModelValue<T>(T t, string strType, string strContent)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strContent);

                PropertyInfo[] pps = GetPropertyInfos(t.GetType());
                Type target = t.GetType();

                var property = t.GetType().GetProperty("PropertyName");


                XmlNode xn = doc.SelectSingleNode("//head");

                bool bResult = false;
                XmlNodeList nodes = xn.ChildNodes;
                if (nodes.Count > 0)
                {
                    //XmlNodeList subs = nodes[0].ChildNodes;
                    foreach (XmlNode v in nodes)
                    {
                        foreach (var vSX in pps)
                        {
                            if (vSX.Name == v.Name)
                            {
                                PropertyInfo targetPP = target.GetProperty(vSX.Name);
                                object objValue = HttpUtility.UrlDecode(v.InnerText);

                                targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);

                                if (v.Name == "code" && v.InnerText == "1")
                                {
                                    bResult = true;
                                }
                            }
                        }
                    }
                }

                if (bResult)
                {
                    XmlNode xn_Result = doc.SelectSingleNode("//vehispara");

                    if (xn_Result != null)
                    {
                        XmlNodeList nodes_Result = xn_Result.ChildNodes;
                        if (nodes_Result.Count > 0)
                        {
                            List<string> lstError = new List<string>();
                            foreach (XmlNode v in nodes_Result)
                            {
                                try
                                {
                                    PropertyInfo targetPP = target.GetProperty(v.Name);
                                    object objValue = HttpUtility.UrlDecode(v.InnerText);

                                    if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                                    {
                                        targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lstError.Add("项目:[" + v.Name + "], 值:[" + v.InnerText + "]转换失败.");
                                    continue;
                                }
                            }

                            #region 日志记录
                            string strCategory = Log.LogType.NetUpDown.ToString();
                            LOG_INFO logInfo = new LOG_INFO();
                            logInfo.Category = strCategory;
                            logInfo.HostName = "";
                            logInfo.IPAddress = "";
                            logInfo.LogTime = DateTime.Now;
                            logInfo.FS_Infor = "";
                            logInfo.JS_Infor = "";
                            logInfo.Log_Infor = strType;
                            foreach (var v in lstError)
                            {
                                logInfo.Log_Infor = logInfo.Log_Infor + v;
                            }

                            logInfo.Name = "上传下载";
                            logInfo.FunName = "ModelReflection.cs -> ResultSetModelValue";

                            Log.WriteLog(logInfo);
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                #region 日志记录
                string strCategory = Log.LogType.NPFail.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = "";
                logInfo.IPAddress = "";
                logInfo.LogTime = DateTime.Now;
                logInfo.FS_Infor = "";
                logInfo.JS_Infor = "";
                logInfo.Log_Infor = ex.Message;
                logInfo.Name = "上传下载";
                logInfo.FunName = "ModelReflection.cs -> ResultSetModelValue";

                Log.WriteLog(logInfo);
                #endregion
            }
            return t;
        }

        public T ResultSetModelValueEx<T>(T t, string strType, string strContent)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(strContent);

                PropertyInfo[] pps = GetPropertyInfos(t.GetType());
                Type target = t.GetType();

                var property = t.GetType().GetProperty("PropertyName");


                XmlNode xn = doc.SelectSingleNode("//" + strType);

                bool bResult = false;
                XmlNodeList nodes = xn.ChildNodes;
                if (nodes.Count > 0)
                {
                    //XmlNodeList subs = nodes[0].ChildNodes;
                    foreach (XmlNode v in nodes)
                    {
                        foreach (var vSX in pps)
                        {
                            if (vSX.Name == v.Name)
                            {
                                PropertyInfo targetPP = target.GetProperty(vSX.Name);
                                object objValue = HttpUtility.UrlDecode(v.InnerText);

                                targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);

                                if (v.Name == "code" && v.InnerText == "1")
                                {
                                    bResult = true;
                                    break;
                                }
                            }
                        }
                    }
                }

                if (bResult)
                {
                    XmlNode xn_Result = doc.SelectSingleNode("//vehispara");

                    if (xn_Result != null)
                    {
                        XmlNodeList nodes_Result = xn_Result.ChildNodes;
                        if (nodes_Result.Count > 0)
                        {
                            List<string> lstError = new List<string>();
                            foreach (XmlNode v in nodes_Result)
                            {
                                try
                                {
                                    foreach (var vSX in pps)
                                    {
                                        if (vSX.Name == v.Name)
                                        {
                                            PropertyInfo targetPP = target.GetProperty(v.Name);
                                            object objValue = HttpUtility.UrlDecode(v.InnerText);

                                            if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                                            {
                                                targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lstError.Add("项目:[" + v.Name + "], 值:[" + v.InnerText + "]转换失败.");
                                    continue;
                                }
                            }

                            #region 日志记录
                            string strCategory = Log.LogType.NetUpDown.ToString();
                            LOG_INFO logInfo = new LOG_INFO();
                            logInfo.Category = strCategory;
                            logInfo.HostName = "";
                            logInfo.IPAddress = "";
                            logInfo.LogTime = DateTime.Now;
                            logInfo.FS_Infor = "";
                            logInfo.JS_Infor = "";
                            logInfo.Log_Infor = strType;
                            foreach (var v in lstError)
                            {
                                logInfo.Log_Infor = logInfo.Log_Infor + v;
                            }

                            logInfo.Name = "上传下载";
                            logInfo.FunName = "ModelReflection.cs -> ResultSetModelValue";

                            Log.WriteLog(logInfo);
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                #region 日志记录
                string strCategory = Log.LogType.NPFail.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = "";
                logInfo.IPAddress = "";
                logInfo.LogTime = DateTime.Now;
                logInfo.FS_Infor = "";
                logInfo.JS_Infor = "";
                logInfo.Log_Infor = ex.Message;
                logInfo.Name = "上传下载";
                logInfo.FunName = "ModelReflection.cs -> ResultSetModelValue";

                Log.WriteLog(logInfo);
                #endregion
            }
            return t;
        }

        public string ResultModelToXML<T>(T t, string strType, bool bChildren = true)
        {
            string strRet = "";
            try
            {
                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();
                GetClassName(t,ref lstParent,ref lstChildren);

                strRet = "";
                strRet += "";
                strRet += "";
                for(int i=0;i<3;i++)
                {
                    strRet += "<" + lstParent[i].Name + ">" + lstParent[i].GetValue(t, null).ToString() + " + lstParent[i].Name + ">";
                }
                strRet += "";
                strRet += "";
                if (bChildren)
                {
                    strRet += "<" + strType + ">";
                    foreach (var v in lstChildren)
                    {
                        if (v.GetValue(t, null) == null)
                        {
                            strRet += "<" + v.Name + "> + v.Name + ">";
                        }
                        else
                        {
                            object objValue = v.GetValue(t, null);
                            //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                            DateTime dateTemp;
                            string strValue;
                            bool bIsDateTime = DateTime.TryParse(objValue.ToString(), out dateTemp);
                            if (IsDateTime(objValue.ToString()))
                            {
                                strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            else
                            {
                                strValue = objValue.ToString();
                            }
                            strRet += "<" + v.Name + ">" + strValue + " + v.Name + ">";
                        }
                    }

                    strRet += " + strType + ">";
                }
                strRet += "";
                strRet += "";
            }
            catch (Exception ex)
            {
            }
            return strRet;
        }
        #endregion

        #region 实体属性反射
        /// 
        /// 实体属性反射
        /// 
        /// 赋值对象
        /// 被赋值对象
        /// 
        /// 
        public void AutoMapping<S, T>(S s, T t)
        {
            PropertyInfo[] pps = GetPropertyInfos(s.GetType());

            Type target = t.GetType();

            foreach (var pp in pps)
            {
                PropertyInfo targetPP = target.GetProperty(pp.Name);
                object value = pp.GetValue(s, null);

                if (targetPP != null && value != null && !string.IsNullOrEmpty(value.ToString()))
                {
                    targetPP.SetValue(t, SD_ChanageType(value,targetPP.PropertyType), null);
                }
            }
        }
        #endregion

        #region PF Request

        public T ReqXMLToModel<T>(T t, string strSigleNode, string strReqContent)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strReqContent);
            Type target = t.GetType();

            #region SetParentValue
            List<NameAndValue> lstAttr = new List<NameAndValue>();
            XmlNode node = doc.SelectSingleNode("//Message");
            for (int i = 0; i < node.Attributes.Count; i++)
            {
                string strName = node.Attributes[i].Name;
                NameAndValue nv = new NameAndValue();
                nv.Name = strName;
                nv.Value = node.Attributes[strName].Value;
                lstAttr.Add(nv);
            }

            XmlNodeList nodeList = node.ChildNodes;

            for (int i = 0; i < nodeList.Count; i++)
            {
                for (int j = 0; j < nodeList[i].Attributes.Count; j++)
                {
                    string strName = nodeList[i].Attributes[j].Name;
                    NameAndValue nv = new NameAndValue();
                    nv.Name = strName;
                    nv.Value = nodeList[i].Attributes[strName].Value;
                    lstAttr.Add(nv);
                }
            }

            foreach (var v in lstAttr)
            {
                PropertyInfo targetPP = target.GetProperty(v.Name);
                object objValue = v.Value;
                if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                {
                    targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                }
            }
            #endregion

            XmlNode subNode = doc.SelectSingleNode("//"+strSigleNode);
            XmlNodeList nodes_Result = subNode.ChildNodes;
            if (nodes_Result.Count > 0)
            {
                //XmlNodeList subs = nodes[0].ChildNodes;
                foreach (XmlNode v in nodes_Result)
                {
                    PropertyInfo targetPP = target.GetProperty(v.Name);
                    object objValue = v.InnerText;
                    if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                    {
                        targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                    }
                }
            }

            return t;
        }

        public string ReqModelToXML<T>(T t, string strType)
        {
            string strRet = "";
            try
            {
                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();

                GetClassName(t,ref lstParent,ref lstChildren);

                strRet += " + lstParent[0].Name + "\">";
                strRet += " + lstParent[1].Name + "\">";
                strRet += "";
                foreach (var v in lstChildren)
                {
                    strRet += "<" + v.Name + ">" + v.GetValue(t, null).ToString() + " + v.Name + ">";
                }
                strRet += "";
                strRet += "";
                strRet += "";
            }
            catch (Exception ex)
            {

            }

            strRet = HttpUtility.UrlEncode(strRet);

            return strRet;
        }
        #endregion

        #region PF Response
        public string RespModelToXML<T>(T t, string strType)
        {
            string strRet = "";
            try
            {
                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();

                GetClassName(t, ref lstParent, ref lstChildren);

                strRet += " + lstParent[0].GetValue(t,null).ToString() + "\">";
                strRet += " + lstParent[1].GetValue(t,null).ToString() + "\">";
                strRet += "";
                foreach (var v in lstChildren)
                {
                    object objValue = v.GetValue(t, null);
                    if (objValue != null)
                    {
                        strRet += "<" + v.Name + ">" + v.GetValue(t, null).ToString() + " + v.Name + ">";
                    }
                }
                strRet += "";
                strRet += "";
                strRet += "";
            }
            catch (Exception ex)
            {

            }

            return strRet;
        }

        public T RespSetModelValue<T>(T t, string strType, string strContent)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strContent);

            List<NameAndValue> lstAttr = new List<NameAndValue>();
            XmlNode node = doc.SelectSingleNode("//Message");
            for (int i = 0; i < node.Attributes.Count; i++)
            {
                string strName = node.Attributes[i].Name;
                NameAndValue nv = new NameAndValue();
                nv.Name = strName;
                nv.Value = node.Attributes[strName].Value;
                lstAttr.Add(nv);
            }

            XmlNodeList nodeList = node.ChildNodes;

            for (int i = 0; i < nodeList.Count; i++)
            {
                for (int j = 0; j < nodeList[i].Attributes.Count; j++)
                {
                    string strName = nodeList[i].Attributes[j].Name;
                    NameAndValue nv = new NameAndValue();
                    nv.Name = strName;
                    nv.Value = nodeList[i].Attributes[strName].Value;
                    lstAttr.Add(nv);
                }
            }

            XmlNode subNote = doc.SelectSingleNode("//"+strType);

            XmlNodeList subNodeList = subNote.ChildNodes;
            for (int i = 0; i < subNodeList.Count; i++)
            {
                string strName = subNodeList[i].Name;
                NameAndValue nv = new NameAndValue();
                nv.Name = strName;
                nv.Value = subNodeList[i].InnerText;
                lstAttr.Add(nv);
            }

            PropertyInfo[] pps = GetPropertyInfos(t.GetType().BaseType);
            Type target = t.GetType();

            foreach (var v in lstAttr)
            {
                PropertyInfo targetPP = target.GetProperty(v.Name);
                object objValue = v.Value;
                if (objValue != null && string.IsNullOrEmpty(objValue.ToString()) == false)
                {
                    targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                }
            }


            return t;
           
        }
        #endregion

        /// 
        /// 转换可空类型
        /// 
        /// 
        /// 
        /// 
        public object SD_ChanageType(object value, Type convertsionType)
        {
            //判断convertsionType类型是否为泛型,因为nullable是泛型类,
            if (convertsionType.IsGenericType &&
                //判断convertsionType是否为nullable泛型类
                convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (value == null || value.ToString().Length == 0)
                {
                    return null;
                }

                //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换
                NullableConverter nullableConverter = new NullableConverter(convertsionType);
                //将convertsionType转换为nullable对的基础基元类型
                convertsionType = nullableConverter.UnderlyingType;
            }
            return Convert.ChangeType(value, convertsionType);
        }

        public T DictionaryToModel<T>(T t, Dictionary<string, string> dic)
        {
            PropertyInfo[] pps = GetPropertyInfos(t.GetType());
            Type target = t.GetType();

            var property = t.GetType().GetProperty("PropertyName");

            List<string> lstKeys = dic.Keys.ToList();

            if (lstKeys.Count > 0)
            {
                foreach(var p in pps)
                { 
                    PropertyInfo targetPP = target.GetProperty(p.Name);
                    if (dic.ContainsKey(p.Name))
                    {
                        object objValue = HttpUtility.UrlDecode(dic[p.Name]);

                        targetPP.SetValue(t, SD_ChanageType(objValue, targetPP.PropertyType), null);
                    }
                }
            }

            return t;
        }

        /// 
        /// model转换成Dictionary
        /// 
        /// 
        /// 
        /// 
        public Dictionary<string, string> ModelToDictionary<T>(T t)
        {
            Dictionary<string, string> dicRet = new Dictionary<string, string>();

            try
            {
                List<PropertyInfo> lstParent = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren = new List<PropertyInfo>();

                GetClassName(t, ref lstParent, ref lstChildren);

                foreach (var v in lstParent)
                {
                    object objValue = v.GetValue(t, null);
                    if (dicRet.ContainsKey(v.Name) == false)
                    {
                        dicRet.Add(v.Name, objValue.ToString());
                    }
                }

                foreach (var v in lstChildren)
                {
                    object objValue = v.GetValue(t, null);
                    if (objValue == null || string.IsNullOrEmpty(objValue.ToString()))
                    {
                        if (dicRet.ContainsKey(v.Name) == false)
                        {
                            dicRet.Add(v.Name, "");
                        }
                    }
                    else
                    {
                        //处理传入参数是否是DateTime类型,如果是,转换成yyyy-MM-dd格式
                        DateTime dateTemp;
                        string strValue;
                        if (IsDateTime(objValue.ToString()))
                        {
                            dateTemp = Convert.ToDateTime(objValue.ToString());
                            strValue = dateTemp.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        else
                        {
                            strValue = objValue.ToString();
                        }

                        if (dicRet.ContainsKey(v.Name) == false)
                        {
                            dicRet.Add(v.Name, strValue);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
 
            }

            return dicRet;
        }
    }
}

你可能感兴趣的:(.NET)