简体   繁体   中英

Add variable to array/list without instancing

I'm creating a guitar tab program.

You select notes (GameObject), type a chord name (string), then press a button to add the "Chord" to a list.

The Chord class is just a String and a list of GameObjects. I use currentChord to hold the current selection/name.

When I select a note, I add it to currentChord.selectedList.

When I type a name, I make it currentChord.name.

Chord currentChord;
List<Chord> allChords;

When I click a button, currentChord gets added to allChords (allChords.Add(currentChord)).

The problem is that it's instanced. So when I click to add a different selection/name, the selection of everything in the allChords.notes list changes...

Do I have to use the "new" keyword?

Yes, you have to use the new keyword.

You are adding the same instance to the list over and over, so you end up with a list of references to the same instance.

Create a new instance from the data in currentChord to add to the list, or add the instance in currentChord to the list and then create a new instance and assign to currentChord .

You may also want to consider the difference between the struct and class keywords which can be used to define Chord . Using struct will provide value-type behavior, where class will provide reference-type behavior.

For example, this is value-type behavior:

struct Chord
{
    public string Name;
}

...

Chord cMajor = new Chord;
cMajor.Name = "C Major";
Chord cMinor = cMajor; // Make a copy of the Chord instance
cMinor.Name = "C Minor";

Assert.That(cMajor.Name, Is.EqualTo("C Major")); // Assertion succeeds

This is reference-type behavior:

class Chord
{
    public string Name;
}

...

Chord cMajor = new Chord;
cMajor.Name = "C Major";
Chord cMinor = cMajor; // No copy of the Chord instance, just another reference
cMinor.Name = "C Minor";

Assert.That(cMajor.Name, Is.EqualTo("C Major")); // Assertion fails
Assert.That(cMajor.Name, Is.EqualTo("C Minor")); // Assertion succeeds

MSDN provides a nice description: http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM