MapperTools.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Linq.Expressions;
  5. namespace Masuit.Tools
  6. {
  7. /// <summary>
  8. /// 工具类
  9. /// </summary>
  10. internal static class MapperTools
  11. {
  12. private static readonly Type _typeString = typeof(string);
  13. private static readonly Type _typeIEnumerable = typeof(IEnumerable);
  14. private static readonly ConcurrentDictionary<Type, Func<object>> _ctors = new ConcurrentDictionary<Type, Func<object>>();
  15. /// <summary>
  16. /// 判断是否是string以外的引用类型
  17. /// </summary>
  18. /// <returns>True:是string以外的引用类型,False:不是string以外的引用类型</returns>
  19. public static bool IsRefTypeExceptString(Type type) => !type.IsValueType && type != _typeString;
  20. /// <summary>
  21. /// 判断是否是string以外的可遍历类型
  22. /// </summary>
  23. /// <returns>True:是string以外的可遍历类型,False:不是string以外的可遍历类型</returns>
  24. public static bool IsIEnumerableExceptString(Type type) => _typeIEnumerable.IsAssignableFrom(type) && type != _typeString;
  25. /// <summary>
  26. /// 创建指定类型实例
  27. /// </summary>
  28. /// <param name="type">类型信息</param>
  29. /// <returns>指定类型的实例</returns>
  30. public static object CreateNewInstance(Type type) => _ctors.GetOrAdd(type, t => Expression.Lambda<Func<object>>(Expression.New(t)).Compile())();
  31. }
  32. }