I've got this useful little method that uses reflection to copy a single class instance. It has the advantage of letting you copy between classes that are not exactly the same, just copying the matching properties. I use it a lot.
public static void ObjectCopy(object source, object target)
{
if (source != null && target != null)
{
foreach (var prop in target.GetType().GetProperties())
{
var FromProp = source.GetType().GetProperty(prop.Name);
if (FromProp != null)
{
prop.SetValue(target, FromProp.GetValue(source));
}
}
}
}
I've now got a requirement to do a similar thing, but with a collection, ie an ObservableCollection or List. I'm struggling to figure out how to do this in a generic routine. I can call the old routine from within the new one to do the collection item copying but handling the collection itself is what I'm struggling with.
Any ideas?
Aucun commentaire:
Enregistrer un commentaire