【问题标题】:Access arraylist from another method in C#从 C# 中的另一个方法访问数组列表
【发布时间】:2014-11-06 07:35:51
【问题描述】:

您好,我是 C# 的初学者,请帮助我编写以下代码:

基本上,我试图将第一个参数作为文件名来打开文件并将单词存储到 ArrayList 数组中(这个类我在另一个类中编写过,它工作正常),第二个参数将是用于与arraylist中的字符串进行长度比较,每当字符串长度与输入字符串匹配时,它将存储在一个新的arraylist wordLength中,并打印到屏幕上。

当我在 Main 方法中编写比较方法时,它工作正常,但我需要访问 arrayList wordLength,因此我编写了一个单独的方法来获取 wordLength 数组作为返回。

如果有人能帮助我理解代码不起作用的原因,那将不胜感激,请说出我拙劣的解释,因为这只是我学习 C# 的第二周,有很多知识在我脑海中闪过,我一直对一些细节感到困惑。提前致谢!

static void Main(string[] args)
{          
    ArrayList array = DataFileReader.DataFile(args[0]);
    String characters = args[0];
}

public static ArrayList WordLength(String characters, ArrayList array)
{

    ArrayList wordLength = new ArrayList();
    foreach (string line in array)
    {
        if (line.Length == characters.Length)
        {
            wordLength.Add(line);
            Console.WriteLine(line);
        }
    }
    return wordLength;
}

【问题讨论】:

  • 旁注 - 不要使用ArrayList。改用通用List<T>
  • 你应该在Main的末尾调用WordLengthWordLength(characters, array)然后使用返回的wordLength
  • 不清楚您要做什么,您是否要将WordLength 的返回值分配给其他东西? (如果是这样,你在第一行代码中做这样的事情)

标签: c# methods arraylist arguments command-line-arguments


【解决方案1】:
namespace Crossword
{
    class Program
    {
        static void Main(string[] args)
        {

                ArrayList array = DataFileReader.DataFile(args[0]);
                String characters = args[0];
                ArrayList wordLength = WordLength(characters,array); // this will pass the variables to your method
        }
        public static ArrayList WordLength(String characters, ArrayList array)
        {

            ArrayList wordLength = new ArrayList();
            foreach (string line in array)
                if (line.Length == characters.Length){
                    wordLength.Add(line);
                    Console.WriteLine(line);
          }

            return wordLength;
        }
}

P.S:试试 Sergey Berezovskiy 所说的“旁注 - 不要使用 ArrayList。改用泛型 List”

【讨论】:

  • 谢谢!我一分钟前才想通,看到这条评论!不过还是谢谢你!
  • 太棒了...快乐的编码... :)
猜你喜欢
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多