如何在 C# 中正确传递数组

本文关键字:数组 | 更新日期: 2023-09-27 17:56:35

嘿,所以我在为课堂开发的程序上遇到了一点麻烦。我认为我犯的错误很小,但我似乎找不到它。似乎我的 sInsults 数组没有正确保存,或者没有正确传递字符串。有人请指出我明显的错误,哈哈。而且不要根据搞笑的侮辱来判断,它们是由我的老师xD指定的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utilities;
using System.IO;
namespace ICA27
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] sNames = { "Al ", "John ", "JD ", "Bill ", "Ross " };
            string[] sVerbs = { "talks to ", "licks ", "runs ", "flushes ", "uses " };
            string[] sObjects = { "safeway carts.", "Microsoft.", "old mops.", "dead cows.", "Vista." };
        string[] sInsults = MakeInsults(sNames, sVerbs, sObjects);
        SaveInsults(sInsults);
    }
    static string[] MakeInsults(string[] sNames, string[] sVerbs, string[] sObjects)
    {
        string sString = "How many insults do you want to make? ";
        int iInput = 0;
        CUtilities.GetValue(out iInput, sString, 5, 100);
        string[] sInsults = new string[iInput];
        Random rNum = new Random();
        for (int i = 0; i< iInput; i++)
        {
            sInsults[i] = sNames[rNum.Next(sNames.Length)] + sVerbs[rNum.Next(sVerbs.Length)] + sObjects[rNum.Next(sObjects.Length)];
        }
        Console.WriteLine("Array of insults have been created!");
        return sInsults;
    }
    static void SaveInsults(string[] sInsults)
    {
        Console.Write("What would you like the file to be named? ");
        string sName = Console.ReadLine();
        StreamWriter swName;
        Console.Write("Would you like to append the file? ");
        string sAnswer = Console.ReadLine();
        sAnswer = sAnswer.ToUpper();
        if ((sAnswer == "YES")||(sAnswer == "Y"))
        {
            swName = new StreamWriter(sName, true);
        }
        else
        {
            swName = new StreamWriter(sName);
        }
        for (int iI = 0; iI < sInsults.Length; iI++)
            swName.WriteLine(sInsults[iI]);
    }
}
}

如何在 C# 中正确传递数组

解决方案 1:您需要关闭StreamWriter实例变量swName

试试这个:

for (int iI = 0; iI < sInsults.Length; iI++)
            swName.WriteLine(sInsults[iI]);
swName.Close(); //add this statement

解决方案 2:

我建议您将StreamWriter Object声明包含在using{}块中,以确保您的对象得到正确处置。

试试这个:

using(StreamWriter swName = new StreamWriter(sName, true))
{
   for (int iI = 0; iI < sInsults.Length; iI++)
    swName.WriteLine(sInsults[iI]);
}

解决方案 3:您仍然可以通过检查 if 条件来使用 using 块。

试试这个:

   bool IsAppend = false;
   if ((sAnswer == "YES")||(sAnswer == "Y"))
    {
        IsAppend = true;
    }
    using(StreamWriter swName = new StreamWriter(sName, IsAppend))
    {
       for (int iI = 0; iI < sInsults.Length; iI++)
        swName.WriteLine(sInsults[iI]);
    }