30 lines
1.1 KiB
C#
30 lines
1.1 KiB
C#
namespace UniversityContracts.Extensions
|
|
{
|
|
public static class ExtensionCast
|
|
{
|
|
/// <summary>
|
|
/// Создает из исходного объекта, объект класса TO копируя в него все общие свойства
|
|
/// </summary>
|
|
/// <typeparam name="TO">The type of the to.</typeparam>
|
|
/// <typeparam name="TFrom">The type of from.</typeparam>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
}
|
|
}
|