添加了将数据库对象列表转换为Model对象的列表

This commit is contained in:
2025-06-23 15:15:10 +08:00
parent c978b92fff
commit 8ee4b7bc05
4 changed files with 51 additions and 24 deletions

33
Helper/CovertHelper.cs Normal file
View File

@@ -0,0 +1,33 @@
using System.Reflection;
namespace PMSWPF.Helper;
public class CovertHelper
{
public static List<TTarget> ConvertList<TSource, TTarget>(List<TSource> sourceList)
{
List<TTarget> targetList = new List<TTarget>();
Type sourceType = typeof(TSource);
Type targetType = typeof(TTarget);
// 获取源类型和目标类型的公共属性
PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] targetProperties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (TSource sourceObject in sourceList)
{
TTarget targetObject = Activator.CreateInstance<TTarget>();
foreach (PropertyInfo targetProperty in targetProperties)
{
PropertyInfo sourceProperty = sourceProperties.FirstOrDefault(p => p.Name == targetProperty.Name && p.PropertyType == targetProperty.PropertyType);
if (sourceProperty!= null)
{
object value = sourceProperty.GetValue(sourceObject);
targetProperty.SetValue(targetObject, value);
}
}
targetList.Add(targetObject);
}
return targetList;
}
}