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

前端 未结 6 1391
醉梦人生
醉梦人生 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:36

    In this case, it would likely be helpful to see how you are validating each item to be sure that the items are unique. If you could show the ToString() method of your class it might help: you might be basing it on something that is actually the same between each of your objects. This might help decide whether you really are getting the same object each time, or if the pieces under consideration really are not unique.

    Also, rather than accessing by index, you should use a foreach loop whenever possible.

    Finally, the items in a list are not universally unique, but rather references to an object that exists elsewhere. If you're trying to check that the retrieved item is unique with respect to an external object, you're going to fail.

    One more thing, I guess: you probably want to have the access on anewList to be private rather than public.

提交回复
热议问题