簡體   English   中英

在 C# 中的 foreach 循環后無法將對象添加到數組中

[英]Can't add objects to an array after a foreach loop in C#

在 foreach 循環之后,我無法將對象附加到數組中。 該對象沒問題,它包含我通過調試發現的所有正確值。

最后,我想要一個自定義的練習對象,其中還包含用戶選擇的自定義練習答案對象數量。 ExerciseAnswer 對象的數組是問題所在。

這是我的方法中有趣的部分:

static void CreateNewExerciseTest()
{
     string? exerciseName = "Test Exercise";
     string? exerciseTopic = "Test";
     string exerciseQuestion = "Does it work?";
     int numberOfAnswers = 2;
     int numberOfApplicableAnswers = 0;
     ExerciseAnswer[] exerciseAnswers = new ExerciseAnswer[2];                    

     foreach (ExerciseAnswer answer in exerciseAnswers)
     {
         int exerciseAnswerId = GenerateId();
         Console.WriteLine("\nEnter a name for this Exercise answer: ");
         string? exerciseAnswerName = Console.ReadLine();
         Console.WriteLine("Enter this answer for the Exercise: ");
         string exerciseAnswerContent = Console.ReadLine();
         Console.WriteLine("Enter y (yes) if this Exercise answer is applicable, 
                            otherwise press n (no) or any other key: ");
         char applicableAnswer = Console.ReadKey().KeyChar;
         bool applicable = ExerciseAnswer.EvaluateExerciseAnswer(applicableAnswer);
         if (applicable == true)
         {
             numberOfApplicableAnswers++;
         }

         ExerciseAnswer exerciseAnswer = new ExerciseAnswer(exerciseAnswerId,   
         exerciseAnswerName, exerciseAnswerContent, applicable);
         exerciseAnswers.Append(exerciseAnswer);
         // ... 
    }
}

這是 GenerateId 方法:

static int GenerateId()
{
    return ++id;
}

數組 exerciseAnswer 不包含它應該包含的 ExerciseAnswer 元素,而上面一行中的 exerciseAnswer 對象包含。 可能問題與exerciseAnswers 和foreach 循環的聲明和初始化有關。

有人有想法嗎?

謝謝!

我相信您正在使用System.Linq命名空間中的Append方法

public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element);

此方法返回一個新的IEnumerable ,其中包含您的exerciceAnswer

通過這段代碼,您可以了解發生了什么:

var result = exerciseAnswers.Append(exerciseAnswer);
Console.WriteLine($"exerciseAnswers count = {exerciseAnswers.Count()}");
Console.WriteLine($"result count = {result.Count()}");

控制台輸出:

exerciseAnswers count = 2
result count = 3

Append 只會追加到數組的現有元素,因為在您的情況下,大小已經定義為 2(new ExerciseAnswer[2]),因此它不會追加任何內容。 您可以做的是擁有一個新數組並將元素添加到其中,或者只是獲取您正在運行循環的元素的索引並在數組中替換相同的元素。 如下所示:- int elementIndex = Array.IndexOf(exerciseAnswers,answer); 練習答案[元素索引] = 練習答案;

暫無
暫無

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

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