List.Add seems to be duplicating entries. What's wrong?

前端 未结 6 1389
醉梦人生
醉梦人生 2020-12-09 23:35

I have a class like this:

public class myClass
{
  public List anewlist = new List;

  public void addToList(myOtherC         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 00:38

    Given the signature of your addToList method:

    public void addToList(myOtherClass tmp)
      {
        anewList.Add(tmp);
      }
    

    Is is possible that in the consumer of that method, you aren't actually creating a new instance?

    You said that you are calling addToList 100 times. Presumably, that is in a loop. At each loop iteration, you will need to create a new instance of "myOtherClass", otherwise, you'll just be updating the same object in memory.

    For example, if you do the below, you will have 100 copies of the same object:

    myOtherClass item = new myOtherClass();
    
    for(int i=0; i < 100; i++)
    {
      item.Property = i;
      addToList(item);
    }
    

    However, if your loop looks like the below, it will work fine:

    myOtherClass item = null;
    for(int i=0; i < 100; i++)
    {
      item = new myOtherClass();
      item.Property = i;
      addToList(item);
    }
    

    Hope that helps!

提交回复
热议问题