C#有关在函数中更改字符串的问题

时间:2018-11-08 18:03:44

标签: c# string

是否可以从另一个值更改字符串?这是我的C#代码:

if (QuestionNum == 1 && inputAnswer == RightAnswer || inputAnswer == RightAnswerLower)
{
    Program.GotQ1Correct = true;
}

我知道在Lua中,我可以将Program.GotQ1Correct = true;部分更改为

Program.GotQ[QuestionNum]Correct = true; 

但是,我只是想知道在C#中是否可行。

编辑

很抱歉,如果我之前不太清楚,那么基本上在上面的lua代码中,它将把GotQ1Correct更改为GotQ2Correct,依此类推,只是想知道是否有类似的简单方法可以在C#中完成数组。

3 个答案:

答案 0 :(得分:1)

似乎满足您的需求

    // assuming 10 questions
    var results = new bool[10];
    var correctAnswers = new string[10]; 
    var studAnswers = new string[10];

    for (int i; i < 10 ; i++)
    {
        if(studAnswer[i].ToLower() == correctAnswers[i].ToLower())
            results[i] = true;

}

或更干净

 results[i] = studAnswer[i].ToLower() == correctAnswers[i].ToLower();

答案 1 :(得分:0)

为更加清楚起见,我可能会做一个字典。

public IDictionary<int, bool> CheckAnswers(Dictionary<int, string> exam, Dictionary<int, string> answers)
{
     var results = new Dictionary<int, bool>();
     for(var index = 0; index < exam.Length; index++)
     {
         if(String.Compare(exam[index], answers[index], true) == 0)
             results.Add(exam[index], true);

          results.Add(exam[index], false);
     }

     return results;
}

var correct = CheckAnswers(..., ...).Where(answer => answer.Value == true).Count();

此解决方案需要改进,但这是对PM答案的很好补充。其中之一至少应为您指明正确的方向。

我推荐字典的原因是您可以通过答案键和考试成绩。让您看到哪些是对的,哪怕是错误的,然后使用提示进行比较即可轻松获得比分。

答案 2 :(得分:-1)

因此,如果您理解您想通过替换访问属性的名称来访问对象的属性? 您可能要检查此帖子 accessing-object-property-as-string

从帖子复制

System.Reflection.PropertyInfo prop =typeof(YourType).GetProperty("PropertyName");

object value = prop.GetValue(yourInstance); ... prop.SetValue(yourInstance, "value");