首先我們可能都同意最好的方法是在自定義對象/實體內部實現複製功能。但請考慮這種情況。我們沒有這個選項,我們也不想編寫特定的函數來完成實體的複製,因爲實體將來會被更改,所以我們的複製函數會失敗。複製不支持複製功能的動態對象的最快方法
這裏被簡化當前實體的版本:
[Serializable]
class MyEntity
{
public MyEntity()
{
}
public MyEntity(int id, string name)
{
this.Id = id;
this.Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
public MyEntity Copy()
{
throw new NotImplementedException();
}
}
覆蓋所有上述要求,我想出了兩個解決方案:
//original...
MyEntity original = new MyEntity() { Id = 1, Name = "demo1" };
//first way to copy object...
List<MyEntity> list = new List<MyEntity>() { original};
MyEntity copy1 = list.ConvertAll(entity => new MyEntity(entity.Id, entity.Name))[0];
//second way to copy object...
byte[] bytes = SerializeEntity(original);
MyEntity copy2 = (MyEntity)DeserializeData(bytes);
byte[] SerializeEntity(object data)
{
byte[] result = null;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, data);
result = ms.ToArray();
}
return result;
}
object DeserializeData(byte[] data)
{
object result = null;
using(MemoryStream ms = new MemoryStream(data))
{
BinaryFormatter formatter = new BinaryFormatter();
result = formatter.Deserialize(ms);
}
return result;
}
現在的問題。背後的最佳解決方案是什麼,以及爲什麼,第一或第二?考慮到上述要求,是否有更好的方法來完成複製?複印件將大量完成。
PS note: 我知道第一種方法基本上已經是Honza指出的複製功能。作爲自定義複製功能,我有點像序列化和接近快速的多功能。
我已經閱讀了幾篇關於AutoMapper的文章,但無法對我的例子中的性能做出任何真正的結論。有些人聲稱這不是所有情況下的最佳解決方案。您能否使用AutoMapper建議任何可能導致性能不佳的指針?此時選擇+1 –