【问题标题】:How to fix overwrites when adding objects to a List将对象添加到列表时如何修复覆盖
【发布时间】:2019-03-27 03:14:19
【问题描述】:

我正在尝试将对象添加到列表中,以便在程序中的其他位置访问。但是,每当我添加一个新对象时,所有以前的对象都会变成最近添加的对象的副本。

我首先尝试使用循环遍历对象,但发现添加新对象时会覆盖列表中已经存在的所有其他对象。我做了一些环顾四周,我认为这与引用内存中的对象有关。但是我不知道如何修复引用。

    List <ObjectTester> holder = new List<ObjectTester>();
    //for(int i =0; i<5; i++)
    //{
    //    ObjectTester objec = new ObjectTester(i.ToString());
    //    holder.Add(objec);
    //    foreach (ObjectTester o in holder)
    //    {
    //        Console.WriteLine(o.ToString());
    //    }
    //}
    holder.Add(new ObjectTester("01"));
    Console.WriteLine(holder[0]);
    holder.Add(new ObjectTester("02"));
    Console.WriteLine(holder[0]);
    Console.WriteLine(holder[1]);
public class ObjectTester
{
    private static string id;

    public ObjectTester(string _id)
    {
        id = _id;
    }
}

在执行注释部分并使用循环显示时,我希望看到 0 1 2 3 4 但是它打印为 4 4 4 4 4 因为所有以前的值都被改变了。 为了测试这一点,我在将它们添加到列表后打印了这些值,输出为: 0 1 1 2 2 2 3 3 3 3 4 4 4 4 4 向我展示它会被列表中的每一个新成员覆盖。

【问题讨论】:

    标签: c# list


    【解决方案1】:

    那是因为您在 ObjectTester 类中的 id 是静态的。

    删除静态关键字。查看有关 static 关键字的 MS 文档:static modifier

    它没有覆盖对象。它覆盖了 id 字段,因为它被标记为静态,它不属于 ObjectTester 类的特定实例。

    【讨论】:

    • 这很有意义!是的,它正在做我现在所期望的。谢谢!
    • 没问题的哥们:)
    猜你喜欢
    • 2015-06-25
    • 2020-10-11
    • 1970-01-01
    • 2021-03-22
    • 2014-02-03
    • 1970-01-01
    • 2022-01-20
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多