删除传递的实例

时间:2015-05-10 12:58:49

标签: c# list oop instance

我现在有点疯狂了。 我将List传递给另一个类的方法,在该类中我使用了不同的变量名(封装)。但这里是: 当我从方法中的列表中删除项目时,项目也会在其他变量中消失!

任何建议我做错了什么?

这里是代码段:

public partial class Form1 : Form
{
   List<Vector> polygonPoints = new List<Vector>();

   private void panel1_Paint(object sender, PaintEventArgs e)
   {
      // Create Convex Hull of polygon Set
         QuickHull qh = new QuickHull();

      // here I pass the list to a method in the class QuickHull
      // here polygonPoints.Count = 5
         List<Vector> hullOfPoints = qh.quickHull(polygonPoints);
      // at this point I get polygonPoints.Count = 3

         ...
   }
}

不同的类QuickHull:

class QuickHull
{
    public List<Vector> quickHull(List<Vector> points)
    {
        List<Vector> convexHull = new List<Vector>();
        ...
        Vector A = points[minPoint];
        Vector B = points[maxPoint];

        convexHull.Add(A);
        convexHull.Add(B);

        // at this point 'polygonPoints' also looses these items
        points.Remove(A);
        points.Remove(B);

        ...
     }
}

我真的不知道该怎么办,因为这一直在起作用,但是从一个时刻到另一个时刻它不再起作用了。

我真的很感激每一个建议。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您看到的是预期的行为。

List<T>是引用类型,因此当您将其传递给方法时,它是对传递的列表的引用。

使用其他变量名称并不能使其成为新列表。它仍然是您引用的列表。

如果您需要列表的本地副本,则需要创建新列表并将项目复制到其中。您可以使用列表构造函数:

List<Vector> local = new List<Vector>(points);

您还可以更改发送到方法中的类型:

public List<Vector> quickHull(IEnumerable<Vector> points)

通过使用IEnumerable<T>接口而不是List<T>类,您将使用限制为仅枚举列表。您仍然可以向方法发送列表,但是您无法错误地更改列表,您仍然可以使用它来创建本地副本。

答案 1 :(得分:1)

当您将List<T>传递给方法时,您传递的值包含对该列表的引用。这意味着您在方法points中接受的参数指向您在调用链中实例化的相同列表。

如果要将引用传递给单独的列表,则需要创建一个新引用:

List<Vector> hullOfPoints = qh.quickHull(polygonPoints.ToList());

您可以在"Passing Reference-Type Parameters"中了解更多信息:

  

引用类型的变量不直接包含其数据;它   包含对其数据的引用。传递引用类型时   参数值,可以更改指向的数据   引用,例如类成员的值。但是,你   不能改变引用本身的值;

答案 2 :(得分:1)

您的问题是您通过了reference&#39;键入然后更改它。相反,您可以创建一个新列表(点)以避免修改先前的输入列表(polygonPoints)。