wcs_serve_wuxikate/WcsMain/Plugins/ObjectCopy.cs
2025-01-03 14:36:27 +08:00

40 lines
1.2 KiB
C#
Raw Permalink 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.

namespace WcsMain.Plugins;
/// <summary>
/// object 拷贝
/// </summary>
/// <remarks>
/// 作者icewint(菻蔃)
/// </remarks>
public class ObjectCopy
{
/// <summary>
/// 将一个类拷贝到另一个类
/// </summary>
/// <typeparam name="IN"></typeparam>
/// <typeparam name="OUT"></typeparam>
/// <param name="input"></param>
/// <returns></returns>
public static OUT CopyProperties<IN, OUT>(IN input) where OUT : class, new() where IN : class, new()
{
// 输出
OUT newClass = Activator.CreateInstance<OUT>();
Type outType = newClass.GetType();
var outProperties = outType.GetProperties();
if (outProperties == default || outProperties.Length == 0) return newClass;
// 输入
Type inType = typeof(IN);
var inProperties = inType.GetProperties();
foreach ( var inProperty in inProperties)
{
var outPropertie = outProperties.FirstOrDefault(s => s.Name == inProperty.Name);
if(outPropertie == default) continue;
outPropertie.SetValue(newClass, inProperty.GetValue(input));
}
return newClass;
}
}