You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何创建存储其他类实例的ArrayList?非泛型报错如何解决?

报错原因

你遇到的The non-generic type 'ArrayList' cannot be used with type arguments报错,是因为当前引用的ArrayList属于System.Collections命名空间下的非泛型集合类,该类是C#早期版本提供的集合实现,本身不支持泛型参数的写法,你为其指定<Record>类型参数就会触发该错误。同时你当前的实例化代码还缺少构造函数的括号,即使类型适配也会触发语法报错。

修复方案

方案1:改用泛型集合List<T>(优先推荐)

这是C#开发中存储同类型元素的首选方案,支持类型安全,无需额外类型转换,性能优于非泛型ArrayList:

  1. 先引入泛型集合命名空间:
using System.Collections.Generic;
  1. 将实例化代码修改为:
List<Record> eList = new List<Record>();

方案2:保留使用非泛型ArrayList(不推荐)

如果你确有需求要使用ArrayList,需要删除泛型参数声明,注意存取元素时需要手动做类型转换:

  1. 引入ArrayList对应的命名空间:
using System.Collections;
  1. 实例化代码修改为:
ArrayList eList = new ArrayList();
  1. 元素存取示例:
// 存入元素
eList.Add(new Record("李", "四", "lisi@example.com"));
// 取出元素需要强制类型转换
Record record = (Record)eList[0];
补充说明

你当前贴出的Record类中的三个字段都是私有属性,如果需要在类外部访问这些字段,建议补充对应的get访问器,示例如下:

public class Record
{
    private String firstname;
    private String lastname;
    private String email;
    public Record(String firstNameIn, String lastNameIn, String emailIn)
    {
        firstname = firstNameIn;
        lastname = lastNameIn;
        email = emailIn;
    }
    // 补充get访问器
    public string FirstName => firstname;
    public string LastName => lastname;
    public string Email => email;
}

内容的提问来源于stack exchange,提问作者Ryan Carney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 03:03:02