English 中文(简体)
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 have 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





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签