using Newtonsoft.Json.Linq;
using System.Text;
namespace Cis.Core;
///
/// 对象拓展
///
[SuppressSniffer]
public static class ObjectExtension
{
///
/// 判断类型是否实现某个泛型
///
/// 类型
/// 泛型类型
/// bool
public static bool HasImplementedRawGeneric(this Type type, Type generic)
{
// 检查接口类型
var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
if (isTheRawGenericType) return true;
// 检查类型
while (type != null && type != typeof(object))
{
isTheRawGenericType = IsTheRawGenericType(type);
if (isTheRawGenericType) return true;
type = type.BaseType;
}
return false;
// 判断逻辑
bool IsTheRawGenericType(Type type) => generic == (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
}
///
/// 将字典转化为QueryString格式
///
///
///
///
public static string ToQueryString(this Dictionary dict, bool urlEncode = true)
{
return string.Join("&", dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}"));
}
///
/// 将字符串URL编码
///
///
///
public static string UrlEncode(this string str)
{
return string.IsNullOrEmpty(str) ? "" : System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);
}
///
/// List转DataTable
///
///
///
///
public static DataTable ToDataTable(this List list)
{
DataTable result = new();
if (list.Count > 0)
{
// result.TableName = list[0].GetType().Name; // 表名赋值
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
Type colType = pi.PropertyType;
if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
colType = colType.GetGenericArguments()[0];
}
if (IsIgnoreColumn(pi))
continue;
result.Columns.Add(pi.Name, colType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new();
foreach (PropertyInfo pi in propertys)
{
if (IsIgnoreColumn(pi))
continue;
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
///
/// 对象序列化成Json字符串
///
///
///
public static string ToJson(this object obj)
{
return JSON.GetJsonSerializer().Serialize(obj);
}
///
/// Json字符串反序列化成对象
///
///
///
///
public static T ToObject(this string json)
{
return JSON.GetJsonSerializer().Deserialize(json);
}
///
/// 字串反序列化成linq对象
///
/// 字串
///
public static JObject ToJObject(this string Json)
{
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
}
///
/// 排除SqlSugar忽略的列
///
///
///
private static bool IsIgnoreColumn(PropertyInfo pi)
{
var sc = pi.GetCustomAttributes(false).FirstOrDefault(u => u.IsIgnore == true);
return sc != null;
}
}