C# 类型转换Dictionary转Model类

/// <summary>
/// 把Model转换为DataRow
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mod"></param>
/// <returns></returns>
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<TKey, TValue, T>(this Dictionary<TKey, TValue> 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
    {
        /// <summary>
        /// 把 Model 转为 字典,是一个和  ModelToDictionary(RuleBase Entity, IModel objModel) 相同算法的函数。
        /// </summary>
        /// <remarks>功能和 FastInvoke 是一样的。针对 WhereClip 会有优化。</remarks>
        /// <param name="objModel"></param>
        /// <returns></returns>
        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);
        }
        /// <summary>
        /// 把 Model 转为 字典。核心函数。
        /// <remarks>
        /// 数据实体推入到数据库时使用,解析如下类型: 
        /// String
        /// Dictionary&lt;ColumnClip, object&gt;
        /// Dictionary&lt;string, object&gt;
        /// Dictionary&lt;string, string&gt;
        /// 类
        /// 值类型结构体
        /// </remarks>
        /// </summary>
        /// <param name="Entity">如果为空,则生成 ConstColumn </param>
        /// <param name="objModel"></param>
        /// <returns></returns>
        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;
        }


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

        //    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);
        }

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

        /// <summary>
        /// 设置字典的属性。
        /// </summary>
        /// <param name="dict">数据源。如果该数据源没有相应字典,则会自动创建</param>
        /// <param name="key">Html Post 的Key,如:  cols[id][sid] </param>
        /// <param name="value">值</param>
        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;
        }


        /// <summary>
        /// 更新Model的一个属性值。Model可以是 字典,Where,类.
        /// </summary>
        /// <param name="objModel">可以是 字典,Where,类.</param>
        /// <param name="Column">要更新的属性</param>
        /// <param name="Value">要更新的值</param>
        /// <returns></returns>
        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;
        }


        /// <summary>
        /// Reader 转为 字典 函数,核心函数。
        /// </summary>
        /// <param name="openReader"></param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// DataRow 转为 字典 函数,核心函数。
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        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();
            }
        }

        /// <summary>
        /// 把 DataTable 转为实体列表。由于DataTable 是一次装载,不对 DataRow 应用权限控制机制
        /// </summary>
        /// <param name="table"></param>
        /// <param name="NewModelFunc"></param>
        /// <returns></returns>
        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<TModel> ToEntityList<T,TModel>(this SelecteClip<T> select )
        //    where T:RuleBase
        //    where TModel:struct
        //{
        //    return select.ToEntityList(() => new TModel());
        //}

        /// <summary>
        /// 把 DataTable 转为实体列表。转换过程不应用权限过滤机制.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 把 DataReader 转为实体。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="openReader"></param>
        /// <returns></returns>
        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());
        }

        / <summary>
        / Reader 转为 字典 函数,核心函数之一。用权限过滤。
        / </summary>
        / <param name="openReader"></param>
        / <returns></returns>
        //public static XmlDictionary<string, object> ToDictionary(this DbDataReader openReader)
        //{
        //    return ToDictionary(openReader, true);
        //}

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


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

        /// <summary>
        /// 把 DataRow 转为实体。由于DataTable 是一次装载,不对 DataRow 应用权限控制机制
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row"></param>
        /// <param name="NewModelFunc">生成默认Model构造器的回调.</param>
        /// <returns></returns>
        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);
        }
        /// <summary>
        /// 把 DbName 转换为 程序 所使用的名称.
        /// </summary>
        /// <remarks>
        /// 如果数据库名称中出现以下 指定的分隔字符 , 则按以下分隔字符 进行分隔, 并把每个部分首字母大写之后进行联接. 分隔字符有:
        /// 1.空格
        /// 2.下划线 _
        /// 3.加号 +
        /// 4.减号 -
        /// 5.#
        /// 6.&amp;
        /// 7.竖线 |
        /// 8.冒号 :
        /// 9.分号 ;
        /// 10.小于号 &lt;
        /// 11.大于号 &gt;
        /// 12.逗号 , 
        /// 13.点号 .
        /// 14.$
        /// 15.左括号
        /// 16.右括号
        /// 
        /// 如果没有出现上述分隔符, 如果数据库名称 全大写,或全小写, 则按首字母大写转换, 否则 返回数据库名称.
        /// </remarks>
        /// <param name="DbName"></param>
        /// <returns></returns>
        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());

        }

        /// <summary>
        /// 把一个 DataTable 转换为 MyOqlSet
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <param name="Rule"></param>
        /// <returns></returns>
        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 t, Dictionary<string, string> 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);
        }

        /// <summary>
        /// 得到子类中所有属性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        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
        /// <summary>
        /// 设置model值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="strContent"></param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 设置model值,仅适用与18C62
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="strContent"></param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 得到18C62子项值
        /// </summary>
        /// <param name="m_Para"></param>
        /// <param name="node"></param>
        /// <param name="nodeName"></param>
        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);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 参数实体转换成XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="strType"></param>
        /// <returns></returns>
        public string ParaModelToXML<T>(T t, string strType)
        {
            string strRet = "";
            try
            {
                strRet = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
                strRet += "<root>";
                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 += "</root>";

                #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;
        }

        /// <summary>
        /// 仅适用与18C81,两重基类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="strType"></param>
        /// <returns></returns>
        public string ParaModelToXML_Ex<T>(T t, string strType)
        {
            string strRet = "";
            try
            {
                strRet = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
                strRet += "<root>";
                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 += "</root>";
            }
            catch (Exception ex)
            {

            }
            return strRet;
        }

        /// <summary>
        /// 仅适用与18C62,两重基类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="strType"></param>
        /// <returns></returns>
        public string ParaModelToXML_18C62(Vehicle_18C62_Para m_18C62, string strType)
        {
            string strRet = "";
            try
            {
                strRet = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
                strRet += "<root>";
                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 += "<rgjyjgs>";
                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 += "<rgjyjg>";

                    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 += "</rgjyjg>";
                }
                strRet += "</rgjyjgs>";
                #endregion

                #region 仪器
                List<PropertyInfo> lstParent_YQ = new List<PropertyInfo>();
                List<PropertyInfo> lstChildren_YQ = new List<PropertyInfo>();
                strRet += "<yqsbjyjgs>";
                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 += "<yqsbjyjg>";

                    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 += "</yqsbjyjg>";
                }
                strRet += "</yqsbjyjgs>";
                #endregion

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

            }
            return strRet;
        }
        #endregion

        /// <summary>
        /// 是否是带时间的日期格式
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        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 = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
                strRet += "<root>";
                strRet += "<head>";
                for(int i=0;i<3;i++)
                {
                    strRet += "<" + lstParent[i].Name + ">" + lstParent[i].GetValue(t, null).ToString() + "</" + lstParent[i].Name + ">";
                }
                strRet += "</head>";
                strRet += "<body>";
                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 += "</body>";
                strRet += "</root>";
            }
            catch (Exception ex)
            {
            }
            return strRet;
        }
        #endregion

        #region 实体属性反射
        /// <summary>
        /// 实体属性反射
        /// </summary>
        /// <typeparam name="S">赋值对象</typeparam>
        /// <typeparam name="T">被赋值对象</typeparam>
        /// <param name="s"></param>
        /// <param name="t"></param>
        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 += "<Message Devecie=\"" + lstParent[0].Name + "\">";
                strRet += "<Request Name=\"" + lstParent[1].Name + "\">";
                strRet += "<Row>";
                foreach (var v in lstChildren)
                {
                    strRet += "<" + v.Name + ">" + v.GetValue(t, null).ToString() + "</" + v.Name + ">";
                }
                strRet += "</Row>";
                strRet += "</Request>";
                strRet += "</Message>";
            }
            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 += "<Message Devecie=\"" + lstParent[0].GetValue(t,null).ToString() + "\">";
                strRet += "<Response Name=\"" + lstParent[1].GetValue(t,null).ToString() + "\">";
                strRet += "<Row>";
                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 += "</Row>";
                strRet += "</Response>";
                strRet += "</Message>";
            }
            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

        /// <summary>
        /// 转换可空类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="convertsionType"></param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// model转换成Dictionary
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值