Delphi has a standard mechanism where one object can be copied from another, paraphrased here as:
class Persistent
{
protected AssignError(Persistent source)
{
throw new ConvertError("Cannot assign a {0} to a {1}", source.GetType().Name, this.GetType().Name);
}
protected virtual AssignTo(Persistent destination)
{
destination.AssignError(this);
}
public virtual Assign(Persistent source)
{
source.AssignTo(this);
}
}
Does the .NET FCL has a canonical syntax of copying objects between each other?
eg:
interface IPersistent
{
public virtual Assign(Object source);
}
public class User : IPersistent
{
private Image avatarThumbnail;
private String name;
public override Assign(Object source)
{
if (source is User)
{
this.avatarThumbnail = source.avatarThumbnail;
this.name = source.Name;
}
else if (source is Image)
avatarThumbnail = (Image)source;
else if (source is DirectoryEntry)
name = ((DirectoryEntry) source).Firstname + " " + ((DirectoryEntry) source).Lastname;
else
throw new AssignError("Assign from {0}", source.GetType());
}
}
Yes i just invented a standard IPersistent
interface; but is there already a mechanism to copy objects between each other?
Update
Note : i am talking about the opposite of cloning an object.
User originalUser = new User();
User theClone = originalUser.Clone();
theClone.Lastname = "Guyer";
originalUser.Assign(theClone);
Or, i don't even need to have a clone at all:
User u = new User();
u.Assign(salesOrder); //copy name/e-mail from the sales order
or
SalesOrder s = new SalesOrder();
s.SalesOrderDate = DateTime.Now;
User customer = new Customer("Kirsten");
s.Assign(user); //copy sold-to/ship-to information from the user
The .NET framework has the ICloneable
interface:
Supports cloning, which creates a new instance of a class with the same value as an existing instance.
And:
The
ICloneable
interface contains one member,Clone
, which is intended to support cloning beyond that supplied byMemberwiseClone
. For more information about cloning, deep versus shallow copies, and examples, see theObject.MemberwiseClone
method.
Update:
As far as I know, there is nothing equivalent to what you want (standard way to copy some values between different objects) in the BCL.
As an alternative to the standard ICloneable interface, you could perform the copy of public properties/fields using reflection. Here's some code written off the top of my head for doing so:
foreach(PropertyInfo mbr in src.GetType().GetProperties())
mbr.SetValue(dst, src.GetValue(src, BindingFlags.GetProperty, null, null, null), BindingFlags.SetProperty, null, null, null)
foreach(FieldInfo mbr in src.GetType().GetFields())
mbr.SetValue(dst, src.GetValue(src, BindingFlags.GetField, null, null, null), BindingFlags.SetField, null, null, null)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.