加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#copy构造函数生成器

发布时间:2020-12-16 03:23:55 所属栏目:百科 来源:网络整理
导读:我想将值从一个对象复制到另一个对象.类似于传递值但具有赋值的东西. 例如: PushPin newValPushPin = oldPushPin; //I want to break the reference here. 有人告诉我为此写一个拷贝构造函数.但是这个类有很多属性,手工编写复制构造函数可能需要一个小时.
我想将值从一个对象复制到另一个对象.类似于传递值但具有赋值的东西.

例如:

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;
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读