mardi 12 février 2019

"For" loop - assign value to properties using PropertyInfo

I am trying to do a quick interview form using a C# Console application.

The form is consisted from questions (that are read from text file using StreamReader) and from answers, that I want to get using Console.ReadLine().

Every answer should be saved into the property defined in the PotentialEmployee class. I do not want to write again same piece of code, so what came to my mind is to do a for loop.

In the for loop, I will always first load a question from StreamReader and then I want to assign an answer to a properties, that are defined in PropertyInfo and every answer should be assigned to another property (like Name, BirthDate, etc.), so I made an index variable.

But sadly, the program is not working properly, as it does not save the informations to the properties.

PotentialEmployee pe = new PotentialEmployee();
PropertyInfo[] pi = pe.GetType().GetProperties();

using (StreamReader InterviewQuestions = new StreamReader(filePath))
            {
                 for (int particularQuestion = 0; particularQuestion < TotalLines(filePath); particularQuestion++)
                {
                    int index = 0;
                    Console.WriteLine(InterviewQuestions.ReadLine());
                    pi[index].SetValue(pe, Console.ReadLine(), null);
                    index++;
                }
            }

So it should look like this:

1) What is your name?

Name = Console.ReadLine()

2) When you were born?

BirthDate = Console.ReadLine()

etc. Could you please help me solve this problem? Thank you!





Aucun commentaire:

Enregistrer un commentaire