C#原型模式

如下:

[Serializable]
public class ModelNewTable : ICloneable
{
    public object Clone()
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            return formatter.Deserialize(stream);
        }
    }
}

 

class Program
{
    static void Main(string[] args)
    {
        var a = new Class1
            {
                a = 1,
                b = "abc",
                c = new StringBuilder("def")
            };
        var b = a.Clone();
        Console.Read();
    }
}
[Serializable]
public class Class1
{
    public int a;
    public string b;
    public StringBuilder c;

    public Class1 Clone()
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            return (Class1)formatter.Deserialize(stream);
        }
    }
}

 

posted on 2013-08-04 18:32  yao2yao4  阅读(137)  评论(0编辑  收藏  举报

导航