如何复制对象的实例? [英] How do I copy an instance of an object?

查看:104
本文介绍了如何复制对象的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些填充List的代码(实际上,它是一系列Lists,但是我们可以假装它只是一个List).想法是将IPackage添加到List中,以获得订单中IPackage的总量.请参见以下代码:

I'm trying to write some code that populates a List (actually, it's a series of Lists, but we can pretend it's just one List). The idea is to add an IPackage to the List for the total quantity of IPackage on order. See the following code:

        ParseExcel pe = new ParseExcel();
        Pinnacle p = pe.ParsePinnacleExcel();
        Rack r = new Rack(20,2,4.5,96,42,6,25*12);
        foreach (PinnacleStock ps in p.StockList.Where(x => 
                 x.ColorCode == "10" && 
                 x.PackageLength == 30.64))
        {
            for (int i = 1; i <= ps.OnOrder; i++)
            {
                r.TryAddPackage((IPackage)ps);
            }
        }

只要IPackage被重复添加到列表中,一切似乎都运行良好.但是,似乎正在添加对象的相同实例,即,每次将对象添加到列表时都不会复制该对象.

Everything seems to be working well, insofar as the IPackage is repeatedly added to the list. However, it seems that the same instance of the object is being added, i.e. the object is not being copied each time it's added to the list.

我需要做什么以确保将对象的 副本 插入列表中,而不仅仅是其他参考?

推荐答案

然后,您需要实现 ICloneable 并替换

Then you need to implement ICloneable and replace

r.TryAddPackage((IPackage)ps);

使用

r.TryAddPackage((IPackage)ps.Clone());

由您决定如何 Clone 应该填充它返回的PinnacleStock的新实例.

It's up to you to decide how Clone should populate the new instance of PinnacleStock that it returns.

在最基本的层面上,您可以说

At the most basic level, you could say

public PinnacleStock : ICloneable {
    public PinnacleStock Clone() {
        return (PinnacleStock)this.MemberwiseClone();
    }
    object ICloneable.Clone() {
        return Clone();
    }
    // details
}

这只会做PinnacleStock的浅表副本.只有您知道这是否是您所在域的正确语义.

This will just do a shallow copy of PinnacleStock. Only you know if this is the correct semantics for your domain.

这篇关于如何复制对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆