How to instantiate a certain number of objects determined at runtime?
So here's my problem...
Let's say I have a simple "Person" class just with "FirstName" and "LastName" attributes.
I want to have a form where the user says how many "Persons" he wants to create and then he fills the name for each one.
E.g. user wants to create 20 persons... he puts 20 on a box clicks the button and starts writing names.
I don't know how many users he is going to create so I can't hav开发者_Python百科e hundreds of object variables in my code like this
Person p1;
Person p2;
(...)
Person p1000;
Just use a
List<Person> lstPersons = new List<Person>();
And then add persons to it with:
lstPersons.Add(new Person());
You can then access the persons with
lstPersons[0]
lstPersons[1]
...
Create an array, sized to whatever number the user inputted. Then you can just loop through the array to instantiate them all.
int numberOfPeople = xxx; // Get this value from the user's input
Person[] people = new Person[numberOfPeople];
for (int i = 0; i < people.Length; i++)
people[i] = new Person();
You need to use a list. You create the list this vay:
var persons=new List<Person>();
and you can dynamically add items this way:
Person thePerson=new Person(...);
persons.Add(thePerson);
You'll probably want to use a collection to Person objects. Try looking at these links
- IList (where T is the generic type Person)
- ICollection
精彩评论