x

学无止境,精益求精

十年河东,十年河西,莫欺少年穷

用于基础返回值类型,如下:

C# 构造基础返回值类型-BaseResponse_其它C# 构造基础返回值类型-BaseResponse_其它_02
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Data.DataCommon
{
    public class BaseResponse
    {
        public BaseResponse()
        {
            this.IsSuccess = false;
            this.ResultCode = -1;
            this.ResultMessage = "请求失败...";
        }
        /// <summary>
        /// 返回信息
        /// </summary>
        public string ResultMessage { get; set; }
        /// <summary>
        /// 返回编码 -1 代表失败  0代表成功
        /// </summary>
        public int ResultCode { get; set; }
        /// <summary>
        /// 处理是否成功
        /// </summary>
        public bool IsSuccess { get; set; }
    }

    public class BaseResponse<T> : BaseResponse
    {
        public T Data { get; set; }

        //public List<T> DataList { get; set; }

        public BaseResponse()
        {
            this.IsSuccess = false;
            this.ResultCode = -1;
            this.ResultMessage = "请求失败...";
        }

        public BaseResponse(T data)
        {
            this.Data = data;
        }
    }

    public class CommonBaseResponse
    {
        #region 重置Response
        public static BaseResponse<T> SetResponse<T>(T Data, bool bol, string Msg = "", int cord = 0)
        {
            BaseResponse<T> response = new BaseResponse<T>();
            response.Data = Data;
            response.IsSuccess = bol;
            response.ResultCode = bol == true ? 0 : -1;
            if (cord != 0)
            {
                response.ResultCode = cord;
            }
            response.ResultMessage = bol == true ? "请求成功..." : "请求失败...";
            if (!string.IsNullOrEmpty(Msg))
            {
                response.ResultMessage = Msg;
            }
            return response;
        }
        public static BaseResponse SetResponse(bool bol, string Msg = "", int cord = 0)
        {
            BaseResponse response = new BaseResponse();
            response.IsSuccess = bol;
            response.ResultCode = bol == true ? 0 : -1;
            if (cord != 0)
            {
                response.ResultCode = cord;
            }
            response.ResultMessage = bol == true ? "请求成功..." : "请求失败...";
            if (!string.IsNullOrEmpty(Msg))
            {
                response.ResultMessage = Msg;
            }
            return response;
        }
        #endregion
    }
}
View Code

下面我们用GET,POST请求如下:

        [HttpPost]
        public ActionResult GetData(DataModel model)
        {
            var result = CommonBaseResponse.SetResponse(true);
            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpGet]
        public ActionResult GetData(string userId)
        {
            var result=CommonBaseResponse.SetResponse(true);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

Ajax 请求如下:

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.get("/Home/GetData?userId=chen", function (result) {
            console.log(result)
        })
    })
</script>

返回值如下:

C# 构造基础返回值类型-BaseResponse_其它_03

Post请求类似,在此不再累述。

如果返回值中带有数据集合,怎么处理?

C#如下:

C# 构造基础返回值类型-BaseResponse_其它C# 构造基础返回值类型-BaseResponse_其它_02
        [HttpGet]
        public ActionResult GetData(string userId)
        {
            List<DataModel> list = new List<DataModel>();
            list.Add(new DataModel() { userId = "081309201", userName = "Jack.Chen", userNo = "08130920701", userSex = "男" });
            list.Add(new DataModel() { userId = "081309202", userName = "LiLi.Chen", userNo = "08130920702", userSex = "女" });
            var result = CommonBaseResponse.SetResponse<List<DataModel>>(list,true);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
View Code

返回值如下:

C# 构造基础返回值类型-BaseResponse_其它_06

综上所述,如此简单。

顺便一个格式化类

C# 构造基础返回值类型-BaseResponse_其它C# 构造基础返回值类型-BaseResponse_其它_02
    public class CommonModelFunc
    {

        public static string FormatDate(Nullable<System.DateTime> date)
        {
            try
            {
                string dateString = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                if (dateString != "0001-01-01")
                {
                    return Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }

        public static string FormatDate(Nullable<System.DateTime> date,string format)
        {
            try
            {
                string dateString = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                if (dateString != "0001-01-01")
                {
                    return Convert.ToDateTime(date).ToString(format);
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }


        public static string FormatStringDate(string date)
        {
            try
            {
                string dateString = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                if (dateString != "0001-01-01")
                {
                    return Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }

        public static string FormatStringDate(string date,string format)
        {
            try
            {
                string dateString = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                if (dateString != "0001-01-01")
                {
                    return Convert.ToDateTime(date).ToString(format);
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }

        public static string FormatMoney(Nullable<decimal> Money)
        {
            if (Money.HasValue)
            {
                return Convert.ToDouble(Money).ToString("0.00");
            }
            else
            {
                return "";
            }
        }

        public static string FormatDateHMS(Nullable<System.DateTime> date)
        {
            try
            {
                string dateString = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                if (dateString != "0001-01-01")
                {
                    return Convert.ToDateTime(date).ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    return "";
                }

            }
            catch
            {
                return "";
            }
        }

        public static string FormatDateChineseHMS(Nullable<System.DateTime> date)
        {
            try
            {
                string dateString = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                if (dateString != "0001-01-01")
                {
                    return Convert.ToDateTime(date).ToString("yyyy年MM月dd日 HH时mm分");
                }
                else
                {
                    return "";
                }

            }
            catch
            {
                return "";
            }
        }
    }
View Code

在此,顺便介绍一个ConvertHelper的类,如下:

C# 构造基础返回值类型-BaseResponse_其它C# 构造基础返回值类型-BaseResponse_其它_02
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
namespace Movit.ZhaoCai.DataCommon
{
    public static class ConvertHelper
    {

        

        /// <summary>
        /// datatow 转换Datatable
        /// </summary>
        /// <param name="drArr"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByDataRows(DataRow[] drArr)
        {
            if (drArr == null || drArr.Length == 0) return null;
            DataTable tmp = drArr[0].Table.Clone();  // 复制DataRow的表结构  
            foreach (DataRow row in drArr)
                tmp.Rows.Add(row.ItemArray);  // 将DataRow添加到DataTable中  
            return tmp;

        }

        public static string ToString(object value)
        {
            if (value != null)
            {
                return value.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public static int ToInt(object value)
        {
            int result = -1;
            if (value != null)
            {
                int.TryParse(value.ToString(), out result);
            }
            return result;
        }

        public static decimal ToDecimal(object value)
        {
            decimal val = 0;
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {

            }
            else
            {
                if (value != null && IsNumber(value.ToString()))
                {

                    decimal.TryParse(value.ToString(), out val);

                }


            }
            return Math.Round(val, 2);
        }
        public static decimal? ToEngineeringquantityDecimal(object value)
        {
            decimal val = 0;
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return null;
            }
            else
            {
                if (value != null && IsNumber(value.ToString()))
                {

                    decimal.TryParse(value.ToString(), out val);

                }


            }
            return Math.Round(val, 2);
        }
        public static DateTime ToDateTime(object value)
        {
            DateTime val = DateTime.Now;
            if (value != null)
            {
                DateTime.TryParse(value.ToString(), out val);
            }
            return val;
        }
        public static double ToDouble(object value)
        {
            double val = 0;
            if (value != null)
            {
                double.TryParse(value.ToString(), out val);
            }
            return val;
        }


        /// <summary>
        /// Add by Allen.Yang,2017年11月20日 17:24:11
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static decimal ConvertToDecimal(this string str)
        {
            decimal d = 0;
            decimal.TryParse(str, out d);
            return d;
        }

        /// <summary>
        /// 金额转换成大写金额
        /// </summary>
        /// <param name="money"></param>
        /// <returns></returns>
        public static string ConvertNumToUpper(string LowerMoney)
        {
            string functionReturnValue = null;
            bool IsNegative = false; // 是否是负数
            if (LowerMoney.Trim().Substring(0, 1) == "-")
            {
                // 是负数则先转为正数
                LowerMoney = LowerMoney.Trim().Remove(0, 1);
                IsNegative = true;
            }
            string strLower = null;
            string strUpart = null;
            string strUpper = null;
            int iTemp = 0;
            // 保留两位小数 123.489→123.49  123.4→123.4
            LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
            if (LowerMoney.IndexOf(".") > 0)
            {
                if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
                {
                    LowerMoney = LowerMoney + "0";
                }
            }
            else
            {
                LowerMoney = LowerMoney + ".00";
            }
            strLower = LowerMoney;
            iTemp = 1;
            strUpper = "";
            while (iTemp <= strLower.Length)
            {
                switch (strLower.Substring(strLower.Length - iTemp, 1))
                {
                    case ".":
                        strUpart = "圆";
                        break;
                    case "0":
                        strUpart = "零";
                        break;
                    case "1":
                        strUpart = "壹";
                        break;
                    case "2":
                        strUpart = "贰";
                        break;
                    case "3":
                        strUpart = "叁";
                        break;
                    case "4":
                        strUpart = "肆";
                        break;
                    case "5":
                        strUpart = "伍";
                        break;
                    case "6":
                        strUpart = "陆";
                        break;
                    case "7":
                        strUpart = "柒";
                        break;
                    case "8":
                        strUpart = "捌";
                        break;
                    case "9":
                        strUpart = "玖";
                        break;
                }

                switch (iTemp)
                {
                    case 1:
                        strUpart = strUpart + "分";
                        break;
                    case 2:
                        strUpart = strUpart + "角";
                        break;
                    case 3:
                        strUpart = strUpart + "";
                        break;
                    case 4:
                        strUpart = strUpart + "";
                        break;
                    case 5:
                        strUpart = strUpart + "拾";
                        break;
                    case 6:
                        strUpart = strUpart + "佰";
                        break;
                    case 7:
                        strUpart = strUpart + "仟";
                        break;
                    case 8:
                        strUpart = strUpart + "万";
                        break;
                    case 9:
                        strUpart = strUpart + "拾";
                        break;
                    case 10:
                        strUpart = strUpart + "佰";
                        break;
                    case 11:
                        strUpart = strUpart + "仟";
                        break;
                    case 12:
                        strUpart = strUpart + "亿";
                        break;
                    case 13:
                        strUpart = strUpart + "拾";
                        break;
                    case 14:
                        strUpart = strUpart + "佰";
                        break;
                    case 15:
                        strUpart = strUpart + "仟";
                        break;
                    case 16:
                        strUpart = strUpart + "万";
                        break;
                    default:
                        strUpart = strUpart + "";
                        break;
                }

                strUpper = strUpart + strUpper;
                iTemp = iTemp + 1;
            }

            strUpper = strUpper.Replace("零拾", "零");
            strUpper = strUpper.Replace("零佰", "零");
            strUpper = strUpper.Replace("零仟", "零");
            strUpper = strUpper.Replace("零零零", "零");
            strUpper = strUpper.Replace("零零", "零");
            strUpper = strUpper.Replace("零角零分", "整");
            strUpper = strUpper.Replace("零分", "整");
            strUpper = strUpper.Replace("零角", "零");
            strUpper = strUpper.Replace("零亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("零亿零万", "亿");
            strUpper = strUpper.Replace("零万零圆", "万圆");
            strUpper = strUpper.Replace("零亿", "亿");
            strUpper = strUpper.Replace("零万", "万");
            strUpper = strUpper.Replace("零圆", "圆");
            strUpper = strUpper.Replace("零零", "零");

            // 对壹圆以下的金额的处理
            if (strUpper.Substring(0, 1) == "圆")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "零")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "角")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "分")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "整")
            {
                strUpper = "零圆整";
            }
            functionReturnValue = strUpper;

            if (IsNegative == true)
            {
                return "负" + functionReturnValue;
            }
            else
            {
                return functionReturnValue;
            }
        }

        /// <summary>
        /// BPM加密字符串key生产规则
        /// </summary>
        /// <param name="str">BPM流程号</param>
        /// <returns></returns>
        public static string NewGetEnCodeStr(string str)
        {
            string enStr = "";
            if (str != null && str.Length > 0)
            {
                str = (((long.Parse(str) * 33 - 666) + 9999) * 888).ToString();
                int l = str.ToString().Length;
                if (l % 2 == 0)//当字符长度为偶数时
                {
                    enStr = str.Remove(l / 2, 2);
                }
                else
                {
                    enStr = str.Remove(l / 2 + 1, 2);//从字符中间+1的位置移除2个字符
                }
            }
            return enStr;
        }

        /// <summary>
        /// 加密字符串2生产规则
        /// </summary>
        /// <param name="content">当前查看用户账号</param>
        /// <returns></returns>
        public static string Encrypt(string content)
        {
            byte[] enData = Encoding.UTF8.GetBytes(content);
            return Convert.ToBase64String(enData);
        }

        /// <summary>
        /// 转换成Datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }

        /// <summary>
        /// 确定指定的类型为空。
        /// </summary>
        private static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// 如果类型为Nullable,返回底层类型,否则返回类型。
        /// </summary>
        private static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }



        /// <summary>
        /// 金额转换成中文大写金额
        /// </summary>
        /// <param name="LowerMoney">eg:10.74</param>
        /// <returns></returns>
        public static string MoneyToUpper(string LowerMoney)
        {
            string functionReturnValue = null;
            bool IsNegative = false; // 是否是负数
            if (LowerMoney.Trim().Substring(0, 1) == "-")
            {
                // 是负数则先转为正数
                LowerMoney = LowerMoney.Trim().Remove(0, 1);
                IsNegative = true;
            }
            string strLower = null;
            string strUpart = null;
            string strUpper = null;
            int iTemp = 0;
            // 保留两位小数 123.489→123.49  123.4→123.4
            LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString();
            if (LowerMoney.IndexOf(".") > 0)
            {
                if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2)
                {
                    LowerMoney = LowerMoney + "0";
                }
            }
            else
            {
                LowerMoney = LowerMoney + ".00";
            }
            strLower = LowerMoney;
            iTemp = 1;
            strUpper = "";
            while (iTemp <= strLower.Length)
            {
                switch (strLower.Substring(strLower.Length - iTemp, 1))
                {
                    case ".":
                        strUpart = "圆";
                        break;
                    case "0":
                        strUpart = "零";
                        break;
                    case "1":
                        strUpart = "壹";
                        break;
                    case "2":
                        strUpart = "贰";
                        break;
                    case "3":
                        strUpart = "叁";
                        break;
                    case "4":
                        strUpart = "肆";
                        break;
                    case "5":
                        strUpart = "伍";
                        break;
                    case "6":
                        strUpart = "陆";
                        break;
                    case "7":
                        strUpart = "柒";
                        break;
                    case "8":
                        strUpart = "捌";
                        break;
                    case "9":
                        strUpart = "玖";
                        break;
                }

                switch (iTemp)
                {
                    case 1:
                        strUpart = strUpart + "分";
                        break;
                    case 2:
                        strUpart = strUpart + "角";
                        break;
                    case 3:
                        strUpart = strUpart + "";
                        break;
                    case 4:
                        strUpart = strUpart + "";
                        break;
                    case 5:
                        strUpart = strUpart + "拾";
                        break;
                    case 6:
                        strUpart = strUpart + "佰";
                        break;
                    case 7:
                        strUpart = strUpart + "仟";
                        break;
                    case 8:
                        strUpart = strUpart + "万";
                        break;
                    case 9:
                        strUpart = strUpart + "拾";
                        break;
                    case 10:
                        strUpart = strUpart + "佰";
                        break;
                    case 11:
                        strUpart = strUpart + "仟";
                        break;
                    case 12:
                        strUpart = strUpart + "亿";
                        break;
                    case 13:
                        strUpart = strUpart + "拾";
                        break;
                    case 14:
                        strUpart = strUpart + "佰";
                        break;
                    case 15:
                        strUpart = strUpart + "仟";
                        break;
                    case 16:
                        strUpart = strUpart + "万";
                        break;
                    default:
                        strUpart = strUpart + "";
                        break;
                }

                strUpper = strUpart + strUpper;
                iTemp = iTemp + 1;
            }

            strUpper = strUpper.Replace("零拾", "零");
            strUpper = strUpper.Replace("零佰", "零");
            strUpper = strUpper.Replace("零仟", "零");
            strUpper = strUpper.Replace("零零零", "零");
            strUpper = strUpper.Replace("零零", "零");
            strUpper = strUpper.Replace("零角零分", "整");
            strUpper = strUpper.Replace("零分", "整");
            strUpper = strUpper.Replace("零角", "零");
            strUpper = strUpper.Replace("零亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("亿零万零圆", "亿圆");
            strUpper = strUpper.Replace("零亿零万", "亿");
            strUpper = strUpper.Replace("零万零圆", "万圆");
            strUpper = strUpper.Replace("零亿", "亿");
            strUpper = strUpper.Replace("零万", "万");
            strUpper = strUpper.Replace("零圆", "圆");
            strUpper = strUpper.Replace("零零", "零");

            // 对壹圆以下的金额的处理
            if (strUpper.Substring(0, 1) == "圆")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "零")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "角")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "分")
            {
                strUpper = strUpper.Substring(1, strUpper.Length - 1);
            }
            if (strUpper.Substring(0, 1) == "整")
            {
                strUpper = "零圆整";
            }
            functionReturnValue = strUpper;

            if (IsNegative == true)
            {
                return "负" + functionReturnValue;
            }
            else
            {
                return functionReturnValue;
            }
        }

        #region  泛型集合和DataSet互转 请注意,使用此方法时请确保实体集合里没有索引属性
        public static IList<T> DataTableToIList<T>(DataTable p_Data)
        {
            // 返回值初始化 
            IList<T> result = new List<T>();

            if (p_Data == null)
                return result;

            for (int j = 0; j < p_Data.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                System.Reflection.PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (System.Reflection.PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < p_Data.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值 
                        string columnName = p_Data.Columns[i].ColumnName.ToUpper();
                        //try
                        //{


                        if (pi.Name.ToUpper().Equals(columnName) || pi.Name.ToUpper().Equals(columnName.Replace("_", string.Empty)))
                        {
                            // 数据库NULL值单独处理 
                            if (p_Data.Rows[j][i] != DBNull.Value && p_Data.Rows[j][i] != null)
                            {
                                if (pi.PropertyType == typeof(Boolean))
                                {
                                    pi.SetValue(_t, Convert.ToBoolean(p_Data.Rows[j][i]), null);
                                }
                                else if (pi.PropertyType == typeof(Int16))
                                {
                                    pi.SetValue(_t, Convert.ToInt16(p_Data.Rows[j][i]), null);
                                }
                                else if (pi.PropertyType == typeof(Int32))
                                {
                                    pi.SetValue(_t, Convert.ToInt32(p_Data.Rows[j][i]), null);
                                }
                                else if (pi.PropertyType == typeof(Decimal))
                                {
                                    pi.SetValue(_t, Convert.ToDecimal(p_Data.Rows[j][i]), null);
                                }
                                else if (pi.PropertyType == typeof(Int32?))
                                {
                                    pi.SetValue(_t, Convert.ToInt32(p_Data.Rows[j][i]), null);
                                }
                                else if (pi.PropertyType == typeof(DateTime))
                                {
                                    pi.SetValue(_t, Convert.ToDateTime(p_Data.Rows[j][i]), null);
                                }
                                else
                                {
                                    pi.SetValue(_t, p_Data.Rows[j][i], null);
                                }
                            }
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                        //}
                        //catch(Exception ex)
                        //{
                        //    string s= columnName;
                        //}
                    }
                }
                result.Add(_t);
            }

            return result;
        }
        /// <summary> 
        /// 集合装换DataSet 
        /// </summary> 
        /// <param name="list">集合</param> 
        /// <returns></returns> 
        public static DataSet ToDataSet(IList p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true);
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }


        /// <summary> 
        /// 泛型集合转换DataSet 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="p_List">泛型集合</param> 
        /// <param name="p_PropertyName">待转换属性名数组</param> 
        /// <returns></returns> 
        public static DataSet ToDataSet<T>(List<T> p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = ToDataTable<T>(p_List);

            result.Tables.Add(_DataTable);
            return result;
        }

        /// <summary> 
        /// DataSet装换为泛型集合 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="p_DataSet">DataSet</param> 
        /// <param name="p_TableIndex">待转换数据表索引</param> 
        /// <returns></returns> 
        public static IList<T> DataSetToIList<T>(DataSet p_DataSet, int p_TableIndex)
        {
            if (p_DataSet == null || p_DataSet.Tables.Count < 0)
                return null;
            if (p_TableIndex > p_DataSet.Tables.Count - 1)
                return null;
            if (p_TableIndex < 0)
                p_TableIndex = 0;

            DataTable p_Data = p_DataSet.Tables[p_TableIndex];
            // 返回值初始化 
            IList<T> result = new List<T>();
            for (int j = 0; j < p_Data.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < p_Data.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值 
                        if (pi.Name.Equals(p_Data.Columns[i].ColumnName))
                        {
                            // 数据库NULL值单独处理 
                            if (p_Data.Rows[j][i] != DBNull.Value)
                                pi.SetValue(_t, p_Data.Rows[j][i], null);
                            else
                                pi.SetValue(_t, null, null);
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }

        /// <summary> 
        /// DataSet装换为泛型集合 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="p_DataSet">DataSet</param> 
        /// <param name="p_TableName">待转换数据表名称</param> 
        /// <returns></returns> 
        public static IList<T> DataSetToIList<T>(DataSet p_DataSet, string p_TableName)
        {
            int _TableIndex = 0;
            if (p_DataSet == null || p_DataSet.Tables.Count < 0)
                return null;
            if (string.IsNullOrEmpty(p_TableName))
                return null;
            for (int i = 0; i < p_DataSet.Tables.Count; i++)
            {
                // 获取Table名称在Tables集合中的索引值 
                if (p_DataSet.Tables[i].TableName.Equals(p_TableName))
                {
                    _TableIndex = i;
                    break;
                }
            }
            return DataSetToIList<T>(p_DataSet, _TableIndex);
        }

        /// <summary>
        /// 将数值税率转换成显示模式(0.05=>5%)
        /// </summary>
        /// <returns></returns>
        public static string RateForShow(string rate)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(rate))
            {
                return result;
            }
            rate = rate.Replace("%", "");
            decimal? i = ToDecimal(rate) * 100;
            if (i.HasValue)
            {
                if (i.Value <= 0)
                {
                    return "其它";
                }

                else
                {
                    return i.Value.ToString("#0") + "%";
                }
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 将金额转换为千分位个是(100,000.12)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DecimalToStringN2(object value)
        {
            decimal val = 0;
            if (value != null)
            {
                val = StringN2ToDecimal(value.ToString());
            }

            return string.Format("{0:N2}", val);
        }

        /// <summary>
        /// 将千分位显示的金额字符转换为金额(100,000.12)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal StringN2ToDecimal(string value)
        {
            decimal val = 0;
            if (!string.IsNullOrEmpty(value))
            {
                value = value.Replace(",", "");
                Decimal.TryParse(value, out val);
            }
            return val;
        }

        #endregion


        /// <summary>
        /// 验证是否是数字
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsNumber(string input)
        {
            string pattern = "^-?\\d+$|^(-?\\d+)(\\.\\d+)?$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(input);
        }

        /// <summary>
        /// 将阿拉伯数字转换成中文数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ConvertArabicNumToChineseNum(object value)
        {
            if (value != null)
            {
                string res = string.Empty;
                switch (value.ToString())
                {
                    case "1":
                        res = "一";
                        break;
                    case "2":
                        res = "二";
                        break;
                    case "3":
                        res = "三";
                        break;
                    case "4":
                        res = "四";
                        break;
                    case "5":
                        res = "五";
                        break;
                    case "6":
                        res = "六";
                        break;
                    case "7":
                        res = "七";
                        break;
                    case "8":
                        res = "八";
                        break;
                    case "9":
                        res = "九";
                        break;
                    case "10":
                        res = "十";
                        break;
                }
                return res;
            }
            else { return string.Empty; }
        }
    }
}
View Code