添加到列表会覆盖C#中的先前对象值

dan*_*odi 0 c# foreach

虽然Stackoverflow上有几个关于这类问题的帖子,但是我已经查看了它们并且没有找到解决我的问题的方法.

在代码中,我将浏览一个带有foreach循环的列表列表,并将创建的元素添加到另一个列表中.虽然在foreach循环中每次迭代都给出一个唯一值,但在它之外的值是相同的.

try
{
    List<Takeoff> takeoffs = new List<Takeoff>();

    List<List<String>> itemTable = queryTable("TK_ITEM", 52);

    foreach (List<String> row in itemTable)
    {
        // Second element in the constructor is Name.
        Takeoff takeoff = new Takeoff(row.ElementAt(0), row.ElementAt(3), row.ElementAt(11), 
            row.ElementAt(17), row.ElementAt(25), row.ElementAt(33), 
            row.ElementAt(37), row.ElementAt(45));

        MessageBox.Show(row.ElementAt(3)); // Each iteration gives an unique value.

        takeoffs.Add(takeoff);
    }

    // Values of both objects are the same.
    MessageBox.Show(takeoffs[0].Name);
    MessageBox.Show(takeoffs[1].Name);

    return takeoffs;
}
catch (Exception)
{
    MessageBox.Show("No material takeoff created!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

    return null;
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了各种添加和显示值的方法,但到目前为止我还没有找到可行的解决方案.

任何人都可以向我指出问题所在吗?

编辑:起飞声明

/*...*/
private static string name;
/*...*/

public Takeoff(string id, string name, string guid, string width, string height, string area, string volume, string count)
{
    /*...*/
    Name = name;
    /*...*/
}

/*...*/

public string Name
{
    get { return name; }
    set { name = value; }
}

/*...*/
Run Code Online (Sandbox Code Playgroud)

Cod*_*ter 8

您的name支持字段是静态的:

private static string name;
Run Code Online (Sandbox Code Playgroud)

不要那样做.只需删除static修饰符,就没有必要了.

静态成员属于该类型,而不是实例.这意味着所有Takeoff共享实例的值相同name,最后分配的值.