ISEbd-22_CourseWork_School/School/SchoolContracts/Extensions/ExtensionsCast.cs

24 lines
775 B
C#
Raw Permalink Normal View History

2024-05-01 17:54:58 +04:00
namespace SchoolContracts.Extensions
{
public static class ExtensionCast
{
public static TO CastWithCommonProperties<TO, TFrom>(this TFrom fromObject)
where TO : class, new()
where TFrom : class, new()
{
TO result = new();
foreach (var propFrom in typeof(TFrom).GetProperties())
{
foreach (var propTo in typeof(TO).GetProperties())
{
if (propFrom.Name == propTo.Name && propFrom.PropertyType == propTo.PropertyType && propTo.CanWrite)
{
propTo.SetValue(result, propFrom.GetValue(fromObject));
}
}
}
return result;
}
}
}