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

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

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

1.Utility

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

csharp 复制代码
public static partial class Utility
{

}

2.Utility.Text

csharp 复制代码
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

csharp 复制代码
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);
        }

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

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

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

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

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

3.Utility.Json

1)IJsonHelper

csharp 复制代码
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

csharp 复制代码
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

csharp 复制代码
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;
        }
    }
}
相关推荐
yngsqq15 分钟前
cad c# 二次开发 ——动态加载dll 文件制作(loada netloadx)
c#
吾与谁归in4 小时前
【C#联合halcon实现绘制ROI功能】
c#·halcon·roi
ling1s5 小时前
C#核心(18)面向对象多态vob
java·开发语言·c#
月巴月巴白勺合鸟月半6 小时前
一个C#开发的APP
c#·web
我曾经是个程序员6 小时前
C#File文件基础操作大全
开发语言·c#
三天不学习7 小时前
C# 中的记录类型简介 【代码之美系列】
后端·c#·微软技术·record·记录类型
Artistation Game7 小时前
一、c#基础
游戏·unity·c#·游戏引擎
chen_2278 小时前
kanzi3.6.10 窗口插件-查找绑定信息
c#·kanzi
Murphy202311 小时前
.net4.0 调用API(form-data)上传文件及传参
开发语言·c#·api·httpwebrequest·form-data·uploadfile·multipart/form-