首页 > 解决方案 > “For”循环 - 使用 PropertyInfo 为属性赋值

问题描述

我正在尝试使用 C# 控制台应用程序进行快速面试。

该表单由问题(使用 StreamReader 从文本文件中读取)和我想使用 Console.ReadLine() 获得的答案组成。

每个答案都应该保存到 PotentialEmployee 类中定义的属性中。我不想再次编写相同的代码,所以我想到的是做一个 for 循环。

在 for 循环中,我总是首先从 StreamReader 加载一个问题,然后我想为 PropertyInfo 中定义的属性分配一个答案,并且每个答案都应分配给另一个属性(如姓名、出生日期等),所以我做了一个索引变量。

但遗憾的是,该程序无法正常运行,因为它没有将信息保存到属性中。

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++;
    }
}

所以它应该是这样的:

1)你叫什么名字?

Name = Console.ReadLine()

2) 你是什么时候出生的?

BirthDate = Console.ReadLine()

等你能帮我解决这个问题吗?谢谢!

编辑:已经发现我的愚蠢错误,该索引将始终为零。无论如何,我将按照建议将其重写为 Dictionary。谢谢大家的答案 :)

标签: c#

解决方案


正如@Damien_The_Unbeliever 所建议的那样,实现上述目标的一种简单方法是将每个问题存储为 aKey并将每个答案存储为 a ValueDictionary这将为您提供一个记录每个问题和响应的结构,并允许您使用问题作为标识符来遍历它们。

下面是一个简单的建议,说明如何将字典添加到PotentialEmployee类中,然后使用控制台记录结果

static void Main(string[] args)
{
    PotentialEmployee pe = new PotentialEmployee();

    using (StreamReader InterviewQuestions = new StreamReader(@"C:\temp\Questions.txt"))
    {
        string question;
        while ((question = InterviewQuestions.ReadLine()) != null)
        {
            Console.WriteLine(question);
            string response = Console.ReadLine();
            pe.Responses.Add(question, response);
        }
    }

    // The following will then go through your results and print them to the console to     
    // demonstrate how to access the dictionary

    Console.WriteLine("Results:");

    foreach(KeyValuePair<string, string> pair in pe.Responses)
    {
        Console.WriteLine($"{pair.Key}: {pair.Value}");
    }
}

...

class PotentialEmployee
{
    // Add a dictionary to your object properties
    public Dictionary<string, string> Responses { get; set; }
    ...

    public PotentialEmployee()
    {
        // Make sure you initialize the Dictionary in the Constructor
        Responses = new Dictionary<string, string>();
    }

    ...
}

推荐阅读