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

时间:2014-04-04 17:47:57

标签: c#

嘿,所以我在上课的课程上遇到了一点麻烦。我认为我所犯的错误很小,但我似乎无法找到它。 好像我的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]);
    }
}
}

1 个答案:

答案 0 :(得分:4)

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

试试这个:

for (int iI = 0; iI < sInsults.Length; iI++)
            swName.WriteLine(sInsults[iI]);

swName.Close(); //add this statement

解决方案2:

我建议您在StreamWriter块中附上using{}对象声明,以确保您的对象得到妥善处理。

试试这个:

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

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

试试这个:

   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]);
    }