Sic.Framework-Nanjing-Baishi/Sicentury.Core/DeepCopyableBase.cs

29 lines
752 B
C#
Raw Normal View History

using System;
using System.Reflection;
namespace Sicentury.Core;
public class DeepCopyableBase
{
public T DeepCopy<T>() where T : DeepCopyableBase, new()
{
var copy = new T();
var type = GetType();
foreach (var propertyInfo in type.GetProperties())
{
if (propertyInfo.CanRead)
{
var originalValue = propertyInfo.GetValue(this);
if (originalValue != null && propertyInfo.CanWrite)
{
propertyInfo.SetValue(copy, originalValue is IDeepCopyable deepCopyable
? deepCopyable.DeepCopy()
: originalValue);
}
}
}
return copy;
}
}