C# 一些工具集优化使用(String,Random,Assembly,Json)

C# 一些工具集优化使用(String,Random,Assembly,Json)

日常开发中会有大量时间接触例如:字符串、随机数、程序集、json等的场景,像字符串使用不当就会产生大量的GC通过封装一些静态的工具方法对这些常用的地方进行适当简单优化

1.Utility

为了使阅读代码的一眼就能看懂代码结构使用如下方式编写

public static partial class Utility
{

}

2.Utility.Text

public static partial class Utility
{
    public static class Text
    {
        private const int StringBuilderCapacity = 1024;
        [ThreadStatic]
        private static StringBuilder m_CacheStringBuilder;

        public static string Format(string format,object arg0)
        {
            if(format == null)
            {
                throw new Exception("Format is invalid.");
            }
            CheckCacheStringBuilder();
            m_CacheStringBuilder.Length = 0;
            m_CacheStringBuilder.AppendFormat(format, arg0);
            return m_CacheStringBuilder.ToString();
        }

        public static string Format(string format, object arg0,object arg1)
        {
            if (format == null)
            {
                throw new Exception("Format is invalid.");
            }
            CheckCacheStringBuilder();
            m_CacheStringBuilder.Length = 0;
            m_CacheStringBuilder.AppendFormat(format, arg0, arg1);
            return m_CacheStringBuilder.ToString();
        }

        public static string Format(string format, object arg0, object arg1,object arg2)
        {
            if (format == null)
            {
                throw new Exception("Format is invalid.");
            }
            CheckCacheStringBuilder();
            m_CacheStringBuilder.Length = 0;
            m_CacheStringBuilder.AppendFormat(format, arg0, arg1, arg2);
            return m_CacheStringBuilder.ToString();
        }

        public static string Format(string format, params object[] args)
        {
            if (format == null)
            {
                throw new Exception("Format is invalid.");
            }
            if(args == null)
            {
                throw new Exception("Args is invalid.");
            }
            CheckCacheStringBuilder();
            m_CacheStringBuilder.Length = 0;
            m_CacheStringBuilder.AppendFormat(format, args);
            return m_CacheStringBuilder.ToString();
        }

        private static void CheckCacheStringBuilder()
        {
            if(m_CacheStringBuilder == null)
            {
                m_CacheStringBuilder = new StringBuilder(StringBuilderCapacity);
            }
        }
    }
}

2.Utility.Random

public static partial class Utility
{
    public static class Random
    {
        private static System.Random m_Random = new System.Random((int)System.DateTime.UtcNow.Ticks);

        public static void SetSeed(int seed)
        {
            m_Random = new System.Random(seed);
        }

        /// 
        /// 返回非负随机数。
        /// 
        /// 大于等于零且小于 System.Int32.MaxValue 的 32 位带符号整数。
        public static int GetRandom()
        {
            return m_Random.Next();
        }

        /// 
        /// 返回一个小于所指定最大值的非负随机数。
        /// 
        /// 要生成的随机数的上界(随机数不能取该上界值)。maxValue 必须大于等于零。
        /// 大于等于零且小于 maxValue 的 32 位带符号整数,即:返回值的范围通常包括零但不包括 maxValue。不过,如果 maxValue 等于零,则返回 maxValue。
        public static int GetRandom(int maxValue)
        {
            return m_Random.Next(maxValue);
        }

        /// 
        /// 返回一个指定范围内的随机数。
        /// 
        /// 返回的随机数的下界(随机数可取该下界值)。
        /// 返回的随机数的上界(随机数不能取该上界值)。maxValue 必须大于等于 minValue。
        /// 一个大于等于 minValue 且小于 maxValue 的 32 位带符号整数,即:返回的值范围包括 minValue 但不包括 maxValue。如果 minValue 等于 maxValue,则返回 minValue。
        public static int GetRandom(int minValue, int maxValue)
        {
            return m_Random.Next(minValue, maxValue);
        }

        /// 
        /// 返回一个介于 0.0 和 1.0 之间的随机数。
        /// 
        /// 大于等于 0.0 并且小于 1.0 的双精度浮点数。
        public static double GetRandomDouble()
        {
            return m_Random.NextDouble();
        }

        /// 
        /// 用随机数填充指定字节数组的元素。
        /// 
        /// 包含随机数的字节数组。
        public static void GetRandomBytes(byte[] buffer)
        {
            m_Random.NextBytes(buffer);
        }
    }
}

3.Utility.Json

1)IJsonHelper

public static partial class Utility
{
    public static partial class Json
    {
        public interface IJsonHelper
        {
            string ToJson(object obj);
            T ToObject<T>(string json);
            object ToObject(Type objectType, string json);
        }
    }
}

2)Json

public static partial class Utility
{
    public static partial class Json
    {
        private static IJsonHelper m_JsonHelper;
        public static void SetJsonHelper(IJsonHelper jsonHelper)
        {
            m_JsonHelper = jsonHelper;
        }

        public static string ToJson(object obj)
        {
            if (m_JsonHelper == null)
            {
                throw new Exception("JSON helper is invalid.");
            }
            try
            {
                return m_JsonHelper.ToJson(obj);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
            return null;
        }

        public static T ToObject<T>(string json)
        {
            if (m_JsonHelper == null)
            {
                throw new Exception("JSON helper is invalid.");
            }
            try
            {
                return m_JsonHelper.ToObject<T>(json);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
            return default;
        }

        public static object ToObject(Type objectType,string json)
        {
            if (m_JsonHelper == null)
            {
                throw new Exception("JSON helper is invalid.");
            }
            try
            {
                return m_JsonHelper.ToObject(objectType, json);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
            return null;
        }
    }
}

4.Utility.Assembly

public static partial class Utility
{
    public static class Assembly
    {
        private static readonly System.Reflection.Assembly[] m_Assemblies = null;
        private static readonly Dictionary<string, Type> m_CacheTypeDic = new Dictionary<string, Type>(StringComparer.Ordinal);
        static Assembly()
        {
            m_Assemblies = AppDomain.CurrentDomain.GetAssemblies();
        }

        public static System.Reflection.Assembly[] GetAssemblies()
        {
            return m_Assemblies;
        }

        public static Type[] GetTypes()
        {
            List<Type> results = new List<Type>();
            foreach (System.Reflection.Assembly assembly in m_Assemblies)
            {
                results.AddRange(assembly.GetTypes());
            }
            return results.ToArray();
        }

        public static Type GetType(string typeName)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                throw new Exception("Type name is invalid.");
            }
            if(m_CacheTypeDic.TryGetValue(typeName,out Type type))
            {
                return type;
            }

            type = Type.GetType(typeName);
            if(type != null)
            {
                m_CacheTypeDic.Add(typeName, type);
                return type;
            }

            foreach (System.Reflection.Assembly assembly in m_Assemblies)
            {
                type = Type.GetType(Text.Format("{0}, {1}", typeName, assembly.FullName));
                if(type != null)
                {
                    m_CacheTypeDic.Add(typeName, type);
                    return type;
                }
            }

            return null;
        }
    }
}

你可能感兴趣的:(C#,c#)