I am trying to implement object deep/shallow cloning service using Reflection. Using the function Clone Simple class is being copied with all the required fields, but in case of SimpleStruct Computed field does not get copied.
What is the difference between struct and class when defining read-only fields, and how this can be solved ?
Thanks in advance.
public T Clone<T>(T source)
{
var obj = Activator.CreateInstance<T>();
var type = source.GetType();
foreach (var property in type.GetProperties())
{
if (!property.IsValid())
continue;
if (property.SetMethod != null)
{
property.SetValue(obj, property.GetValue(source));
}
}
foreach (var field in type.GetFields())
{
if (field.IsPublic == false || !field.IsValid())
continue;
field.SetValue(obj, field.GetValue(source));
}
return obj;
}
public struct SimpleStruct
{
public int I;
public string S { get; set; }
[Cloneable(CloningMode.Ignore)]
public string Ignored { get; set; }
public string Computed => S + I;
public SimpleStruct(int i, string s)
{
I = i;
S = s;
Ignored = null;
}
}
public class Simple
{
public int I;
public string S { get; set; }
[Cloneable(CloningMode.Ignore)]
public string Ignored { get; set; }
[Cloneable(CloningMode.Shallow)]
public object Shallow { get; set; }
public string Computed => S + I + Shallow;
}
Aucun commentaire:
Enregistrer un commentaire