C#
Deep Copy
가게주인
2022. 6. 22. 13:49
밑에 적어놓은 건 교수님 코드
예외 사항 많아서 그대로 쓰진 못하고 코드 연구할 때에만 쓰기!
public static T DeepCopy<T>(this T obj) where T : new()
{
Type type = obj.GetType();
if(type.IsClass)
{
T.clone = new T();
FieldInfo[] fields = type.GetFields();
foreach(FieldInfo field in fields)
{
field.SetValue(clone, (field.GetValue(obj)).DeepCopy());
}
return (T)clone;
}
return (T)obj;
}
}
단점: 클래스가 멤버를 자기 자신으로 갖고 있을 때 무한반복해버림