簡體   English   中英

“For”循環 - 使用 PropertyInfo 為屬性賦值

[英]"For" loop - assign value to properties using PropertyInfo

我正在嘗試使用 C# 控制台應用程序進行快速面試。

該表單由問題(使用 StreamReader 從文本文件中讀取)和我想使用 Console.ReadLine() 獲得的答案組成。

每個答案都應保存到 PotentialEmployee 類中定義的屬性中。 我不想再寫同一段代碼,所以我想到的是做一個 for 循環。

在 for 循環中,我將始終首先從 StreamReader 加載一個問題,然后我想為在 PropertyInfo 中定義的屬性分配一個答案,並且每個答案都應分配給另一個屬性(如 Name、BirthDate 等),所以我做了一個索引變量。

但遺憾的是,該程序無法正常工作,因為它沒有將信息保存到屬性中。

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()

等你能幫我解決這個問題嗎? 謝謝!

編輯:已經發現我的愚蠢錯誤,該索引將始終為零。 無論如何,我將按照建議將其重寫為字典。 謝謝大家的答案 :)

如@Damien_The_Unbeliever 所建議的那樣,實現上述目標的一種簡單方法是將每個問題存儲為Key ,將每個答案存儲為DictionaryValue 這將為您提供一個記錄每個問題和響應的結構,並允許您使用問題作為標識符來遍歷它們。

下面是一個簡單的建議,說明如何向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>();
    }

    ...
}

首先,您需要確保要存儲答案的文件和屬性中的問題序列應該具有相同的序列。

這對我有用

PotentialEmployee pe = new PotentialEmployee();
PropertyInfo[] pi = pe.GetType().GetProperties();
string filePath = "D:\\Questions.txt";
using (StreamReader InterviewQuestions = new StreamReader(filePath))
{
    for (int particularQuestion = 0; particularQuestion < TotalLines(filePath);
         particularQuestion++)
    {                    
        Console.WriteLine(InterviewQuestions.ReadLine());
        pi[particularQuestion].SetValue(pe, Console.ReadLine(), null);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM