Falcon.SugarApi/Falcon.SugarApi/ObjectExtend.cs
2022-07-14 09:01:38 +08:00

65 lines
2.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Falcon.SugarApi
{
/// <summary>
/// Object类型扩展方法
/// </summary>
public static class ObjectExtend
{
/// <summary>
/// 对source进行浅表复制并复制到target中
/// </summary>
/// <typeparam name="TSource">原对象类型</typeparam>
/// <param name="source">原对象</param>
/// <param name="target">目标对象</param>
public static TSource CloneTo<TSource>(this TSource source, [NotNull] object target) 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 s.Name equals t.Name
select new { s, t };
foreach (var item in all) {
//item.t.SetValue(target, Convert.ChangeType(item.s.GetValue(source), item.t.PropertyType));
item.t.SetValue(target,item.s.GetValue(source).ChangeType(item.t.PropertyType));
}
return source;
}
/// <summary>
/// 从原对象中浅表复制属性值
/// </summary>
/// <typeparam name="Ttarget">目标对象类型</typeparam>
/// <param name="target">目标对象</param>
/// <param name="source">原对象</param>
/// <returns>目标对象</returns>
public static Ttarget CloneFrom<Ttarget>(this Ttarget target, object source) where Ttarget : class {
source.CloneTo(target);
return target;
}
/// <summary>
/// 将对象转换成另一类型如果转换失败可能返回null。
/// </summary>
/// <param name="source">原对象</param>
/// <param name="targetType">目标类型</param>
/// <returns>转换后的类型</returns>
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);
}
}
}