using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Text
{
    public static class CommonExtend
    {
        public static string EnumToString<T>(this Enum @enum)
        {
            return Enum.GetName(typeof(T), @enum);
        }
        public static T GetEnum<T>(this string value)
        {
            return value.StringIsEmpty() ? default(T) : (T)Enum.Parse(typeof(T), value);

        }

        public static short GetShort(this byte[] bt, int index)
        {
            int itemnumber = 0;
            itemnumber = bt[index];
            itemnumber <<= 8;
            itemnumber = bt[index+1] | itemnumber;
            return (short)itemnumber; 
        }
        public static string ToClone(this string value)
        {
            return value.Clone().ToString();
        }
        public static bool SaveXml<T>(this T t, string path)
        {

            try
            {
                if (t == null)
                {
                    return false;
                }
                System.Xml.Serialization.XmlSerializer xmlSerializer = new Xml.Serialization.XmlSerializer(t.GetType());
                System.IO.StreamWriter fileStream = new IO.StreamWriter(path, false);
                xmlSerializer.Serialize(fileStream, t);
                fileStream.Close();
                //  YG.Log.Instance.WriteLogAdd(string.Format("序列化对象:{0}成功 并写入文件：{1}", t.GetType(), path));

                return true;
            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd(string.Format("序列化对象:{0}失败:{1}", t.GetType(), ex.Message));
                return false;
            }
        }
        public static T OpenXml<T>(this T t, string path)
        {
            try
            {

                System.Xml.Serialization.XmlSerializer xmlSerializer = new Xml.Serialization.XmlSerializer(t.GetType());
                System.IO.StreamReader fileStream = new IO.StreamReader(path);

                //   YG.Log.Instance.WriteLogAdd(string.Format("反序列化对象:{0}成功 并写入文件：{1}", t.GetType(), path));
                t = (T)xmlSerializer.Deserialize(fileStream);

                fileStream.Close();
                return t;

            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd(string.Format("反序列化对象:{0}失败:{1}", t.GetType(), ex.Message));
                return default(T);
            }

        }
    }
}
