1

I need a semi-shallow copy of an object. Under my original design I used MemberwiseClone to catch all the simple stuff and then I specifically copied the classes to the extent that they needed to be copied. (Some of them are inherently static and most of the rest are containers holding static items.) I didn't like the long list of copies but there's no way around that.

Now, however, I find myself needing to create a descendent object--do I now have to go back and copy all those fields that previously I was copying with MemberwiseClone?

Or am I missing some better workaround for this?

4

1 回答 1

4

我发现最简单的克隆方法是使用序列化。这显然只适用于[Serializable]实现或实现的类ISerializable

这是一个通用的通用扩展,可用于使任何可序列化类的对象可克隆:

public static T Clone<T>(this T source)
{
    if (source == default(T))
    {
        return default(T);
    } else {
        IFormatter formatter = new BinaryFormatter();
        Stream ms = new MemoryStream();
        using (ms)
        {
            formatter.Serialize(ms, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T) formatter.Deserialize(ms);
        }
    }
}
于 2011-07-25T05:10:01.717 回答