using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text.Json;
namespace Falcon.SugarApi
{
///
/// Object类型扩展方法
///
public static class ObjectExtend
{
///
/// 对source进行浅表复制,并复制到target中
///
/// 原对象类型
/// 原对象
/// 目标对象
/// 忽略大小写。默认false不忽略大小写
public static TSource CloneTo(this TSource source,[NotNull] object target,bool ignoreCase = false) where TSource : class {
_ = source ?? throw new ArgumentNullException(nameof(source));
_ = target ?? throw new ArgumentNullException(nameof(target));
var all = from s in source.GetType().GetProperties()
join t in target.GetType().GetProperties()
on ignoreCase ? s.Name.ToLower() : s.Name equals ignoreCase ? t.Name.ToLower() : t.Name
select new { s,t };
foreach(var item in all) {
item.t.SetValue(target,item.s.GetValue(source).ChangeType(item.t.PropertyType));
}
return source;
}
///
/// 从原对象中浅表复制属性值
///
/// 目标对象类型
/// 目标对象
/// 原对象
/// 忽略大小写。默认false不忽略大小写
/// 目标对象
public static Ttarget CloneFrom(this Ttarget target,object source,bool ignoreCase = false) where Ttarget : class {
source.CloneTo(target,ignoreCase);
return target;
}
///
/// 将对象转换成另一类型,如果转换失败可能返回null。
///
/// 原对象
/// 目标类型
/// 转换后的类型
public static object? ChangeType(this object? source,Type targetType) {
if(targetType == null) {
throw new ArgumentNullException("targetType");
}
if(source == null) {
return null;
}
if(targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
NullableConverter nullableConverter = new NullableConverter(targetType);
targetType = nullableConverter.UnderlyingType;
}
return Convert.ChangeType(source,targetType);
}
///
/// 如果对象为null则抛出异常
///
/// 检测对象
/// 对象本身
/// 对象为null
public static object? ThrowNullExceptionWhenNull(this object? obj) {
if(obj == null) {
throw new ArgumentNullException();
}
return obj;
}
///
/// 扩展对象,获取属性枚举s
///
/// 要扩展的对象
///
public static IEnumerable ExpandProperties(this object obj) {
foreach(PropertyInfo p in obj.GetType().GetProperties()) {
yield return new ExpandPropertyInfo {
TargetObj = obj,
Name = p.Name,
Type = p.PropertyType,
Value = p.CanRead ? p.GetValue(obj) : null,
SetValue = new Action