我想将值从一个对象复制到另一个对象.类似于传递值但具有赋值的东西.
例如:
PushPin newValPushPin = oldPushPin; //I want to break the reference here.
Run Code Online (Sandbox Code Playgroud)
有人告诉我为此写一个拷贝构造函数.但是这个类有很多属性,手工编写复制构造函数可能需要一个小时.
注意:Silverlight中不提供ICloneable.
如果可以将要克隆的对象标记为Serializable,则可以使用内存中序列化来创建副本.检查以下代码,它的优点是它也适用于其他类型的对象,并且每次添加,删除或更改属性时都不必更改复制构造函数或复制代码:
class Program
{
static void Main(string[] args)
{
var foo = new Foo(10, "test", new Bar("Detail 1"), new Bar("Detail 2"));
var clonedFoo = foo.Clone();
Console.WriteLine("Id {0} Bar count {1}", clonedFoo.Id, clonedFoo.Bars.Count());
}
}
public static class ClonerExtensions
{
public static TObject Clone<TObject>(this TObject toClone)
{
var formatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
formatter.Serialize(memoryStream, toClone);
memoryStream.Position = 0;
return (TObject) formatter.Deserialize(memoryStream);
}
}
}
[Serializable]
public class Foo
{
public int Id { get; private set; }
public string Name { get; private set; }
public IEnumerable<Bar> Bars { get; private set; }
public Foo(int id, string name, params Bar[] bars)
{
Id = id;
Name = name;
Bars = bars;
}
}
[Serializable]
public class Bar
{
public string Detail { get; private set; }
public Bar(string detail)
{
Detail = detail;
}
}
Run Code Online (Sandbox Code Playgroud)
有一个受保护的成员叫做“ MemberwiseClone ”,你可以在你的班级里写这个……
public MyClass Clone(){
return (MyClass)this.MemberwiseClone();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以访问..
MyClass newObject = oldObject.Clone();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1942 次 |
| 最近记录: |