【问题标题】:Don't know how to fix "The non-generic type 'ArrayList' cannot be used with type arguments"?不知道如何解决“非泛型类型 'ArrayList' 不能与类型参数一起使用”?
【发布时间】:2021-04-29 17:48:55
【问题描述】:

我正在尝试将文本文件读入 ArrayList。如果我在此行中包含:“ArrayList<String> messages = new ArrayList();”,则会收到非通用错误,但如果我删除它,则会在返回行中收到此错误:

无法隐式转换类型“System.Collections.ArrayList”

using System.Collections;
using System;
using System.IO;

namespace mhpreader
{
    internal class NewBaseType
    { 
        public ArrayList messages = new ArrayList();

        internal NewMhpReader ReadMessages()
        {
            {
                throw new NotImplementedException();
            }
        }
    }
    internal class NewMhpReader : NewBaseType
    {
        private string _FilePath;

        public NewMhpReader(string FilePath)
        {
            this._FilePath = FilePath;
        }

        private string line;

        public NewMhpReader[] ReadMessages(string nMessages)
        {
             ArrayList<String> messages = new ArrayList();
             //List<TextReader> messages = new List<string>;
             using (StreamReader stre = new StreamReader(_FilePath))
             {
                   while ((line = stre.ReadLine()) != null)
                   {
                         messages.Add(line);
                         Console.WriteLine(messages);
                   }
             }
             return messages;
        }
    }
}

【问题讨论】:

  • 使用List<T> 而不是ArrayList,后者已过时。请参阅 ArrayList 文档中的 the remarks
  • 我将消息切换为 List,但在返回消息时仍然出现此错误;行“不能隐式转换类型'System.Collections.Generic.List'”
  • 你没有返回你告诉你的方法期望的类型..

标签: c# arraylist


【解决方案1】:

有几件事可以帮助您:

  1. 我会按照其他人的建议删除 ArrayList 并将其替换为 List

  2. 您的 List TextReader 需要是 List 字符串

  3. 将您的 Console.WriteLine(messages) 更改为 Console.WriteLine(line)

  4. 确保在 usings 中包含泛型命名空间(用于 List)。

  5. 确保返回正确类型的列表字符串。这是导致您看到的编译器错误的原因。

             public List<string> ReadMessages(string nMessages)
             {
                 List<string> messages = new List<string>;
                 using (StreamReader stre = new StreamReader(_FilePath))
                     {
                         while ((line = stre.ReadLine()) != null)
                         {
                             messages.Add(line);
                             Console.WriteLine(line);
                         }
                     }
                 return messages;
             }
    

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    相关资源
    最近更新 更多