【问题标题】:C# Question on a changing a string in a functionC#关于在函数中更改字符串的问题
【发布时间】:2018-11-08 18:03:44
【问题描述】:

是否可以从另一个值更改字符串?这是我的 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# 中是否有类似的简单方法可以做到这一点数组。

【问题讨论】:

  • 嗨,马克斯。欢迎来到 StackOverflow。真的很难理解你在问什么,因为你发布了一小部分代码,忽略了大部分上下文。你能创建一个Minimal, Complete and Verifiable example吗?
  • 好吧,你到底要什么? Program.GotQ[QuestionNum] looks to be an array. Are you asking about arrays? Can't you create an Question[] questions = { new Question("什么是 2+2", "4"); };` 还是什么?
  • 是的,当然有可能,但您的问题根本不清楚。你似乎在问“我可以使用一系列问题吗”回答“是的,你可以”
  • 您可以修改字符串的值,但由于字符串是不可变的,原始引用仍然存在于内存中,直到垃圾收集器拾取该内存块。字符串的每个实例或修改都会使用您的值创建一个新的内存块。
  • @Greg - 我认为问题的“字符串”部分无关紧要。示例代码没有对字符串做任何事情

标签: c# string


【解决方案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();

【讨论】:

  • 最简单的方法,只是不确定 OP 知道他想要什么。
【解决方案2】:

为了更清楚,我可能会做一本字典。

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 答案的一个很好的补充。其中之一至少应该为您指明正确的方向。

我推荐字典的原因是你可以通过答案键和考试结果。让你看看哪些是正确的,哪些是错误的,然后使用一个计数来获得分数相对容易。

【讨论】:

    【解决方案3】:

    那么如果理解你想通过替换访问属性的名称来访问对象的属性? 您可能想查看这篇文章 accessing-object-property-as-string

    从帖子中复制

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多