是否有与Delphi的Assign / AssignTo相同的.NET语法?

时间:2011-12-21 20:31:20

标签: c# .net variable-assignment

Delphi有一个标准机制,其中一个对象可以从另一个对象复制,在此解释为:

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);
    }
}

.NET FCL是否具有在彼此之间复制对象的规范语法?

e.g:

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());
    }
}

是的,我刚发明了一个标准的IPersistent界面;但是,是否已经存在一种在彼此之间复制对象的机制?

更新

注意:我在谈论克隆对象的相反

User originalUser = new User();
User theClone = originalUser.Clone();
theClone.Lastname = "Guyer";

originalUser.Assign(theClone);

或者,我根本不需要克隆:

User u = new User();
u.Assign(salesOrder); //copy name/e-mail from the sales order

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

2 个答案:

答案 0 :(得分:2)

.NET框架具有ICloneable接口:

  

支持克隆,它创建一个具有与现有实例相同值的类的新实例。

  

ICloneable界面包含一个成员Clone,该成员旨在支持超出MemberwiseClone提供的克隆。有关克隆,深拷贝和浅拷贝以及示例的详细信息,请参阅Object.MemberwiseClone方法。


更新

据我所知,在BCL中没有任何东西与你想要的东西相同(在不同对象之间复制一些值的标准方法)。

答案 1 :(得分:0)

作为标准ICloneable接口的替代方案,您可以使用反射执行公共属性/字段的副本。这里有一些代码写在我的头顶:

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)