コード例 #1
0
        /// <summary>
        /// 类型转换(精准强大)
        /// </summary>
        /// <param name="value">值处理</param>
        /// <param name="t">类型</param>
        /// <returns></returns>
        public static object ChangeType(object value, Type t)
        {
            if (t == null)
            {
                return(null);
            }
            if (t.FullName == "System.Type")
            {
                return((Type)value);
            }
            string strValue = Convert.ToString(value);

            if (t.IsGenericType && t.Name.StartsWith("Nullable"))
            {
                t = Nullable.GetUnderlyingType(t);
                if (strValue == "")
                {
                    return(null);
                }
            }
            if (t.Name == "String")
            {
                if (value is byte[])
                {
                    return(Convert.ToBase64String((byte[])value));
                }
                return(strValue);
            }
            if (t.FullName == "System.Text.StringBuilder")
            {
                return(value as StringBuilder);
            }
            if (t.FullName == "System.Text.Encoding")
            {
                return(value as Encoding);
            }
            if (strValue == "")
            {
                return(Activator.CreateInstance(t));
            }
            else if (t.IsValueType)
            {
                if (t.Name == "DateTime")
                {
                    switch (strValue.ToLower().TrimEnd(')', '('))
                    {
                    case "now":
                    case "getdate":
                    case "current_timestamp":
                        return(DateTime.Now);
                    }
                    if (DateTime.Parse(strValue) == DateTime.MinValue)
                    {
                        return((DateTime)SqlDateTime.MinValue);
                    }
                    return(Convert.ChangeType(value, t));//这里用value,避免丢失毫秒
                }
                if (t.Name == "Guid")
                {
                    if (strValue == SqlValue.Guid || strValue.StartsWith("newid"))
                    {
                        return(Guid.NewGuid());
                    }
                    return(new Guid(strValue));
                }
                else if (t.Name.StartsWith("Int"))
                {
                    switch (strValue.ToLower())
                    {
                    case "true":
                        return(1);

                    case "false":
                        return(0);
                    }
                    if (strValue.IndexOf('.') > -1)
                    {
                        strValue = strValue.Split('.')[0];
                    }
                    else if (value.GetType().IsEnum)
                    {
                        return((int)value);
                    }
                }
                else if (t.Name == "Double" || t.Name == "Single")
                {
                    switch (strValue.ToLower())
                    {
                    case "infinity":
                    case "正无穷大":
                        return(double.PositiveInfinity);

                    case "-infinity":
                    case "负无穷大":
                        return(double.NegativeInfinity);
                    }
                }
                else if (t.Name == "Boolean")
                {
                    switch (strValue.ToLower())
                    {
                    case "yes":
                    case "true":
                    case "1":
                    case "on":
                    case "是":
                        return(true);

                    case "no":
                    case "false":
                    case "0":
                    case "":
                    case "否":
                    default:
                        return(false);
                    }
                }
                else if (t.IsEnum)
                {
                    return(Enum.Parse(t, strValue, true));
                }
                return(Convert.ChangeType(strValue, t));
            }
            else
            {
                Type valueType = value.GetType();
                //if(valueType.IsEnum && t.is)

                if (valueType.FullName != t.FullName)
                {
                    switch (ReflectTool.GetSystemType(ref t))
                    {
                    case SysType.Custom:

                        return(MDataRow.CreateFrom(strValue).ToEntity(t));

                    case SysType.Generic:
                        if (t.Name.StartsWith("List"))
                        {
                            return(MDataTable.CreateFrom(strValue).ToList(t));
                        }
                        break;

                    case SysType.Array:
                        if (t.Name == "Byte[]")
                        {
                            if (valueType.Name == "String")
                            {
                                return(Convert.FromBase64String(strValue));
                            }
                            using (MemoryStream ms = new MemoryStream())
                            {
                                new BinaryFormatter().Serialize(ms, value);
                                return(ms.ToArray());
                            }
                        }
                        break;
                    }
                }
                return(Convert.ChangeType(value, t));
            }
        }
コード例 #2
0
        /// <summary>
        /// 类型转换(精准强大)
        /// </summary>
        /// <param name="value">值处理</param>
        /// <param name="t">类型</param>
        /// <returns></returns>
        public static object ChangeType(object value, Type t)
        {
            if (t == null)
            {
                return(null);
            }
            string strValue = Convert.ToString(value);

            if (t.IsEnum)
            {
                if (strValue != "")
                {
                    if (Enum.IsDefined(t, strValue))
                    {
                        return(Enum.Parse(t, strValue));
                    }
                    int v = 0;
                    if (int.TryParse(strValue, out v))
                    {
                        object v1 = Enum.Parse(t, strValue);
                        if (v1.ToString() != strValue)
                        {
                            return(v1);
                        }
                    }
                    string[] names = Enum.GetNames(t);
                    string   lower = strValue.ToLower();
                    foreach (string name in names)
                    {
                        if (name.ToLower() == lower)
                        {
                            return(Enum.Parse(t, name));
                        }
                    }
                }

                //取第一个值。
                string firstKey = Enum.GetName(t, -1);
                if (!string.IsNullOrEmpty(firstKey))
                {
                    return(Enum.Parse(t, firstKey));
                }
                return(Enum.Parse(t, Enum.GetNames(t)[0]));
            }
            if (value == null)
            {
                return(null);
            }
            if (t.FullName == "System.Object")
            {
                return(value);
            }
            if (t.FullName == "System.Type")
            {
                return((Type)value);
            }
            if (t.FullName == "System.IO.Stream" && value is HttpPostedFile)
            {
                return(((HttpPostedFile)value).InputStream);
            }

            if (t.IsGenericType && t.Name.StartsWith("Nullable"))
            {
                t = Nullable.GetUnderlyingType(t);
                if (strValue == "")
                {
                    return(null);
                }
            }
            if (t.Name == "String")
            {
                if (value is byte[])
                {
                    return(Convert.ToBase64String((byte[])value));
                }
                return(strValue);
            }
            if (t.FullName == "System.Text.StringBuilder")
            {
                return(value as StringBuilder);
            }
            if (t.FullName == "System.Text.Encoding")
            {
                return(value as Encoding);
            }
            if (strValue == "")
            {
                if (t.Name.EndsWith("[]"))
                {
                    return(null);
                }
                return(Activator.CreateInstance(t));
            }
            else if (t.IsValueType)
            {
                if (t.Name == "DateTime")
                {
                    switch (strValue.ToLower().TrimEnd(')', '('))
                    {
                    case "now":
                    case "getdate":
                    case "current_timestamp":
                        return(DateTime.Now);
                    }
                    if (DateTime.Parse(strValue) == DateTime.MinValue)
                    {
                        return((DateTime)SqlDateTime.MinValue);
                    }
                    return(Convert.ChangeType(value, t));//这里用value,避免丢失毫秒
                }
                else if (t.Name == "Guid")
                {
                    if (strValue == SqlValue.Guid || strValue.StartsWith("newid"))
                    {
                        return(Guid.NewGuid());
                    }
                    return(new Guid(strValue));
                }
                else
                {
                    switch (strValue.ToLower())
                    {
                    case "yes":
                    case "true":
                    case "1":
                    case "on":
                    case "是":
                        if (t.Name == "Boolean")
                        {
                            return(true);
                        }
                        else
                        {
                            strValue = "1";
                        }
                        break;

                    case "no":
                    case "false":
                    case "0":
                    case "":
                    case "否":
                        if (t.Name == "Boolean")
                        {
                            return(false);
                        }
                        else
                        {
                            strValue = "0";
                        }
                        break;

                    case "infinity":
                    case "正无穷大":
                        if (t.Name == "Double" || t.Name == "Single")
                        {
                            return(double.PositiveInfinity);
                        }
                        break;

                    case "-infinity":
                    case "负无穷大":
                        if (t.Name == "Double" || t.Name == "Single")
                        {
                            return(double.NegativeInfinity);
                        }
                        break;

                    default:
                        if (t.Name == "Boolean")
                        {
                            return(false);
                        }
                        break;
                    }

                    if (t.Name.StartsWith("Int") || t.Name == "Byte")
                    {
                        if (strValue.IndexOf('.') > -1)//11.22
                        {
                            strValue = strValue.Split('.')[0];
                        }
                        else if (value.GetType().IsEnum)
                        {
                            return((int)value);
                        }
                    }
                }
                return(Convert.ChangeType(strValue, t));
            }
            else
            {
                Type valueType = value.GetType();
                //if(valueType.IsEnum && t.is)

                if (valueType.FullName != t.FullName)
                {
                    switch (ReflectTool.GetSystemType(ref t))
                    {
                    case SysType.Custom:

                        return(MDataRow.CreateFrom(strValue).ToEntity(t));

                    case SysType.Generic:
                        if (t.Name.StartsWith("List"))
                        {
                            return(MDataTable.CreateFrom(strValue).ToList(t));
                        }
                        break;

                    case SysType.Array:
                        if (t.Name == "Byte[]")
                        {
                            if (valueType.Name == "String")
                            {
                                return(Convert.FromBase64String(strValue));
                            }
                            using (MemoryStream ms = new MemoryStream())
                            {
                                new BinaryFormatter().Serialize(ms, value);
                                return(ms.ToArray());
                            }
                        }
                        break;
                    }
                }
                return(Convert.ChangeType(value, t));
            }
        }
コード例 #3
0
ファイル: JsonSplit.cs プロジェクト: jiszen/cyqdata
        internal static List <T> SplitList <T>(string json, int topN, EscapeOp op)
        {
            List <T> result = new List <T>();

            if (!string.IsNullOrEmpty(json))
            {
                Type t = typeof(T);
                // object entity = Activator.CreateInstance(t);
                T    entity      = Activator.CreateInstance <T>();
                bool hasSetValue = false;
                List <PropertyInfo> pInfoList = ReflectTool.GetPropertyList(t);
                List <FieldInfo>    fInfoList = ReflectTool.GetFieldList(t);
                //string key = string.Empty;
                StringBuilder key   = new StringBuilder(32);
                StringBuilder value = new StringBuilder();
                CharState     cs    = new CharState(false);
                try
                {
                    #region 核心逻辑
                    char c;
                    for (int i = 0; i < json.Length; i++)
                    {
                        c = json[i];
                        if (!cs.IsKeyword(c)) //设置关键符号状态。
                        {
                            if (cs.jsonStart) //Json进行中。。。
                            {
                                if (cs.keyStart > 0)
                                {
                                    key.Append(c);
                                }
                                else if (cs.valueStart > 0)
                                {
                                    value.Append(c);
                                }
                            }
                            else if (!cs.arrayStart)//json结束,又不是数组,则退出。
                            {
                                break;
                            }
                        }
                        else if (cs.childrenStart)//正常字符,值状态下。
                        {
                            int temp;
                            int length = GetValueLength(false, json, i, false, out temp);//优化后,速度快了10倍
                            value.Length = 0;
                            value.Append(json.Substring(i, length));
                            cs.childrenStart = false;
                            cs.valueStart    = 0;
                            cs.setDicValue   = true;
                            i = i + length - 1;
                        }
                        if (cs.setDicValue)//设置键值对。
                        {
                            if (key.Length > 0)
                            {
                                string k      = key.ToString();
                                string val    = value.ToString();//.TrimEnd('\r', '\n', '\t');
                                bool   isNull = json[i - 5] == ':' && json[i] != '"' && val.Length == 4 && val == "null";
                                if (isNull)
                                {
                                    val = "";
                                }
                                else
                                {
                                    val = JsonHelper.UnEscape(val, op);
                                }
                                object o = val;
                                foreach (PropertyInfo p in pInfoList)
                                {
                                    if (String.Compare(p.Name, k, StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        if (p.CanWrite)
                                        {
                                            if (p.PropertyType.Name != "String")
                                            {
                                                o = ConvertTool.ChangeType(val, p.PropertyType);
                                            }
                                            p.SetValue(entity, o, null);
                                            hasSetValue = true;
                                        }
                                        break;
                                    }
                                }
                                if (!hasSetValue && fInfoList.Count > 0)
                                {
                                    foreach (FieldInfo f in fInfoList)
                                    {
                                        if (String.Compare(f.Name, k, StringComparison.OrdinalIgnoreCase) == 0)
                                        {
                                            if (f.FieldType.Name != "String")
                                            {
                                                o = ConvertTool.ChangeType(val, f.FieldType);
                                            }
                                            f.SetValue(entity, o);
                                            hasSetValue = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            cs.setDicValue = false;
                            key.Length     = 0;
                            value.Length   = 0;
                        }

                        if (!cs.jsonStart && hasSetValue)
                        {
                            result.Add(entity);
                            if (topN > 0 && result.Count >= topN)
                            {
                                return(result);
                            }
                            if (cs.arrayStart)//处理数组。
                            {
                                entity      = Activator.CreateInstance <T>();
                                hasSetValue = false;
                            }
                        }
                    }
                    #endregion
                }
                catch (Exception err)
                {
                    Log.Write(err, LogType.Error);
                }
                finally
                {
                    key   = null;
                    value = null;
                }
            }
            return(result);
        }
コード例 #4
0
ファイル: ConvertTool.cs プロジェクト: jiszen/cyqdata
        /// <summary>
        /// DbDataReader To List
        /// </summary>
        internal static List <T> ChangeReaderToList <T>(DbDataReader reader)
        {
            Type     t    = typeof(T);
            List <T> list = new List <T>();

            if (t.Name == "MDataRow")
            {
                MDataTable dt = reader;
                foreach (object row in dt.Rows)
                {
                    list.Add((T)row);
                }
            }
            else if (reader != null)
            {
                #region Reader


                if (reader.HasRows)
                {
                    Dictionary <string, Type> kv = new Dictionary <string, Type>(StringComparer.OrdinalIgnoreCase);
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        kv.Add(reader.GetName(i), reader.GetFieldType(i));
                    }


                    List <PropertyInfo> pInfoList = ReflectTool.GetPropertyList(t);
                    List <FieldInfo>    fInfoList = ReflectTool.GetFieldList(t);
                    while (reader.Read())
                    {
                        T obj = Activator.CreateInstance <T>();

                        if (pInfoList.Count > 0)
                        {
                            foreach (PropertyInfo p in pInfoList)//遍历实体
                            {
                                if (p.CanWrite && kv.ContainsKey(p.Name))
                                {
                                    object objValue = reader[p.Name];
                                    if (objValue != null && objValue != DBNull.Value)
                                    {
                                        if (p.PropertyType != kv[p.Name])
                                        {
                                            objValue = ChangeType(objValue, p.PropertyType);//尽量避免类型转换
                                        }
                                        p.SetValue(obj, objValue, null);
                                    }
                                }
                            }
                        }
                        if (fInfoList.Count > 0)
                        {
                            foreach (FieldInfo f in fInfoList)//遍历实体
                            {
                                if (kv.ContainsKey(f.Name))
                                {
                                    object objValue = reader[f.Name];
                                    if (objValue != null && objValue != DBNull.Value)
                                    {
                                        if (f.FieldType != kv[f.Name])
                                        {
                                            objValue = ChangeType(objValue, f.FieldType);//尽量避免类型转换
                                        }
                                        f.SetValue(obj, objValue);
                                    }
                                }
                            }
                        }
                        list.Add(obj);
                    }
                    kv.Clear();
                    kv = null;
                }
                reader.Close();
                reader.Dispose();
                reader = null;
                #endregion
            }
            return(list);
            //return List<default(T)>;
        }
コード例 #5
0
ファイル: ConvertTool.cs プロジェクト: orm-core-group/cyqdata
        /// <summary>
        /// 类型转换(精准强大)
        /// </summary>
        /// <param name="value">值处理</param>
        /// <param name="t">类型</param>
        /// <returns></returns>
        public static object ChangeType(object value, Type t)
        {
            if (t == null)
            {
                return(null);
            }
            if (t.FullName == "System.Type")
            {
                return((Type)value);
            }
            string strValue = Convert.ToString(value);

            if (t.IsGenericType && t.Name.StartsWith("Nullable"))
            {
                t = Nullable.GetUnderlyingType(t);
                if (strValue == "")
                {
                    return(null);
                }
            }
            if (t.Name == "String")
            {
                return(strValue);
            }
            if (t.FullName == "System.Text.StringBuilder")
            {
                return(value as StringBuilder);
            }
            if (t.FullName == "System.Text.Encoding")
            {
                return(value as Encoding);
            }
            if (strValue == "")
            {
                return(Activator.CreateInstance(t));
            }
            else if (t.IsValueType)
            {
                if (t.Name == "DateTime")
                {
                    return(Convert.ChangeType(value, t));//这里用value,避免丢失毫秒
                }
                if (t.Name == "Guid")
                {
                    return(new Guid(strValue));
                }
                else if (t.Name.StartsWith("Int"))
                {
                    if (strValue.IndexOf('.') > -1)
                    {
                        strValue = strValue.Split('.')[0];
                    }
                    else if (value.GetType().IsEnum)
                    {
                        return((int)value);
                    }
                }
                else if (t.Name == "Boolean")
                {
                    switch (strValue.ToLower())
                    {
                    case "yes":
                    case "true":
                    case "1":
                    case "on":
                    case "是":
                        return(true);

                    case "no":
                    case "false":
                    case "0":
                    case "":
                    case "否":
                    default:
                        return(false);
                    }
                }
                else if (t.IsEnum)
                {
                    return(Enum.Parse(t, strValue, true));
                }
                return(Convert.ChangeType(strValue, t));
            }
            else
            {
                //Type valueType = value.GetType();
                //if(valueType.IsEnum && t.is)
                if (value.GetType().FullName != t.FullName)
                {
                    switch (ReflectTool.GetSystemType(ref t))
                    {
                    case SysType.Custom:

                        return(MDataRow.CreateFrom(strValue).ToEntity(t));

                    case SysType.Generic:
                        if (t.Name.StartsWith("List"))
                        {
                            return(MDataTable.CreateFrom(strValue).ToList(t));
                        }
                        break;

                    case SysType.Array:
                        if (t.Name == "Byte[]" && value.GetType().Name != t.Name)
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                new BinaryFormatter().Serialize(ms, value);
                                return(ms.ToArray());
                            }
                        }
                        break;
                    }
                }
                return(Convert.ChangeType(value, t));
            }
        }