微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c#copy构造函数生成器

我想将值从一个对象复制到另一个对象.类似于传递值但具有赋值的东西.

例如:

pushpin newValpushpin = oldpushpin; //I want to break the reference here.

有人告诉我为此写一个拷贝构造函数.但是这个类有很多属性,手工编写复制构造函数可能需要一个小时.

>有没有更好的方法通过值将对象分配给另一个对象?
>如果没有,是否有复制构造函数生成器?

注意: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;
        }
    }

原文地址:https://www.jb51.cc/c/111567.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐