克隆对象在C#中无法正常工作

时间:2014-12-26 10:44:13

标签: c# clone

我在复制对象方面遇到了麻烦。

我想复制 object1 ,然后在不更改 object1 的情况下更改 object2

// I'm cloning lower.Rebar object here
upper.Rebar = lower.Rebar.Clone();

// When I make changes to upper.Rebar, lower.Rebar gets changed too.
upper.Rebar.Polyline.Points.RemoveAll(p => p.Y < breaklevel);

// Here is how I'm cloning the lower.Rebar object
public ColumnElevationRebar Clone()
{
    var obj = new ColumnElevationRebar();

    obj.CanBeContinued = CanBeContinued;
    obj.CanBeSpliced = CanBeContinued;
    obj.ConnectionType = ConnectionType;
    obj.SpliceLength = SpliceLength;
    obj.Polyline = Polyline;

    return obj;
}

班级的定义

public class ColumnElevationRebar
    {
        public ColumnElevationRebar Clone()
        {
            var obj = new ColumnElevationRebar();

            obj.CanBeContinued = CanBeContinued;
            obj.CanBeSpliced = CanBeContinued;
            obj.ConnectionType = ConnectionType;
            obj.SpliceLength = SpliceLength;
            obj.Polyline = Polyline;

            return obj;
        }

        private double splicelength;
        public double SpliceLength
        {
            get { return splicelength; }
            set { splicelength = Arithmetics.Ceiling(value, 100); }
        }

        public RebarConnectionType ConnectionType { get; set; }

        public bool CanBeSpliced;
        public bool CanBeContinued;

        public bool IsSelected;

        public Polyline Polyline { get; set; }

        public double Length
        {
            get { return Arithmetics.Ceiling(Polyline.Length, 100); }
        }
    }


public class Polyline
{
    public Polyline Clone()
    {
        var obj = new Polyline {Points = this.Points};
        return obj;
    }

    public Polyline()
    {
        Points = new List<_2DPoint>();
    }

    public List<_2DPoint> Points { get; set; }
}

2 个答案:

答案 0 :(得分:1)

似乎Polyline是一个类,而不是原始类型。如果是这样,也可以为Polyline创建克隆方法并使用它。

答案 1 :(得分:1)

您只制作对象的浅表副本。如果需要深层复制,则应克隆所有非值类型对象。根据名称,我假设只有Polyline需要克隆:

public ColumnElevationRebar Clone()
{
    var obj = new ColumnElevationRebar();

    obj.CanBeContinued = CanBeContinued;
    obj.CanBeSpliced = CanBeContinued;
    obj.ConnectionType = ConnectionType;
    obj.SpliceLength = SpliceLength;
    obj.Polyline = Polyline.Clone();

    return obj;
}

只需在Polyline对象中定义Clone方法(我不知道该类)。

编辑: 您在Polyline课程中犯了同样的错误,您还需要克隆列表:

public Polyline Clone()
{
    var obj = new Polyline {Points = new List<_2DPoint>(this.Points)};
    return obj;
}