2025-06-23 15:15:10 +08:00
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace PMSWPF.Helper;
|
|
|
|
|
|
|
|
|
|
public class CovertHelper
|
|
|
|
|
{
|
|
|
|
|
public static List<TTarget> ConvertList<TSource, TTarget>(List<TSource> sourceList)
|
|
|
|
|
{
|
2025-06-23 17:01:06 +08:00
|
|
|
var targetList = new List<TTarget>();
|
|
|
|
|
var sourceType = typeof(TSource);
|
|
|
|
|
var targetType = typeof(TTarget);
|
2025-06-23 15:15:10 +08:00
|
|
|
|
|
|
|
|
// 获取源类型和目标类型的公共属性
|
2025-06-23 17:01:06 +08:00
|
|
|
var sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
|
|
|
|
var targetProperties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
2025-06-23 15:15:10 +08:00
|
|
|
|
2025-06-23 17:01:06 +08:00
|
|
|
foreach (var sourceObject in sourceList)
|
2025-06-23 15:15:10 +08:00
|
|
|
{
|
2025-06-23 17:01:06 +08:00
|
|
|
var targetObject = Activator.CreateInstance<TTarget>();
|
|
|
|
|
foreach (var targetProperty in targetProperties)
|
2025-06-23 15:15:10 +08:00
|
|
|
{
|
2025-06-23 17:01:06 +08:00
|
|
|
var sourceProperty = sourceProperties.FirstOrDefault(p =>
|
|
|
|
|
p.Name == targetProperty.Name && p.PropertyType == targetProperty.PropertyType);
|
|
|
|
|
if (sourceProperty != null)
|
2025-06-23 15:15:10 +08:00
|
|
|
{
|
2025-06-23 17:01:06 +08:00
|
|
|
var value = sourceProperty.GetValue(sourceObject);
|
2025-06-23 15:15:10 +08:00
|
|
|
targetProperty.SetValue(targetObject, value);
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-06-23 17:01:06 +08:00
|
|
|
|
2025-06-23 15:15:10 +08:00
|
|
|
targetList.Add(targetObject);
|
|
|
|
|
}
|
2025-06-23 17:01:06 +08:00
|
|
|
|
2025-06-23 15:15:10 +08:00
|
|
|
return targetList;
|
|
|
|
|
}
|
|
|
|
|
}
|