I'm working on a small app on .NET, I need to point the same data with 2 diferent lists, I'm wondering if perhaps the memory is duplicated, for example

public class Person
{
    public string name;
    public int age;

    ....
    public Person(name, age)
    {
        this.name = name;
        this.age = age;
    }
}

SortedList<string> names;
SortedList<int> ages;

Person person1 = new Person("juan",23);

names.add("juan",person1);
ages.add(23,person1);

I guess that .NET as Java will not duplicate the object Person, so it will be keeped, so if I do this:

names("juan").age = 24

Will change the object in both lists.

Is it right?

Thank you.

有帮助吗?

解决方案

Because Person is a class, you are only putting a reference into the list, so each list will have a reference to the same person. The Person object will indeed not be duplicated, and names["juan"] will de-reference the original object.

However! That doesn't make the code faultless:

  • there might be more than one person aged 23; SortedList<,> won't like that
  • changing the age via names["juan"] won't automatically update ages; ages[24] will fail

If Person was a struct, then the Person would be copied every time you assign it (but: this is not a good candidate for a struct; don't do that)

其他提示

To test reference equality, you can always do:

bool equals = ReferenceEquals(obj1, obj2); 
//in your case, obj1 = names["juan"], and obj2 = ages[23]

If reference is the same that means any change on it will be reflected on variables that reference to the same object.


In your case, yes they are just the same reference in both lists.. So if you do anything on the reference, be it on person1, names["juan"] or ages[23] it will be reflected everywhere. That said, your collection should look like:

Person person1 = new Person();
SortedList<string, Person> names = new SortedList<string, Person>();
SortedList<int, Person> ages = new SortedList<int, Person>();

names.Add("juan", person1);
ages.Add(23, person1);

//names["juan"].age
//ages[23].age 
//etc

Yes, This Will change the object in both lists.

if you want to provident this i suggest to overload the "=" operator (explicit )

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top