using System;
using System.Collections.Generic;
using System.Text;

namespace Performance.Infrastructure
{
    /// <summary>
    /// 类型转换 
    /// </summary>
    public static class ConvertHelper
    {

        public static int TryInt(string inValue, int defaultValue = default(int))
        {
            int ret = defaultValue;
            int.TryParse(inValue, out ret);
            return ret;
        }

        public static long TryLong(string inValue, long defaultValue = default(int))
        {
            long ret = defaultValue;
            long.TryParse(inValue, out ret);
            return ret;
        }

        public static decimal TryDecimal(string inValue, decimal defaultValue = default(decimal))
        {
            decimal ret = defaultValue;
            decimal.TryParse(inValue, out ret);
            return ret;
        }

        public static DateTime TryDateTime(string inValue, DateTime defaultValue = default(DateTime))
        {
            DateTime ret = defaultValue;
            DateTime.TryParse(inValue, out ret);
            return ret;
        }


        /// <summary>
        /// 返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="param"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T To<T>(object value, T defaultValue = default(T))
        {
            try
            {
                var t = typeof(T);
                //兼容可空类型转换
                if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    if (value == null)
                    {
                        return default(T);
                    }

                    t = Nullable.GetUnderlyingType(t);
                }

                return (T)Convert.ChangeType(value, t);
            }
            catch
            {
                return defaultValue;
            }
        }



        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name = "T"></typeparam>
        /// <param name = "value">The value.</param>
        /// <param name = "defaultValue">The default value.</param>
        /// <param name = "ignoreException">if set to <c>true</c> ignore any exception.</param>
        /// <returns>The target type</returns>
        public static T To<T>(object value, T defaultValue, bool ignoreException)
        {
            if (ignoreException)
            {
                try
                {
                    return To<T>(value);
                }
                catch
                {
                    return defaultValue;
                }
            }
            return To<T>(value);
        }


    }
}