c# - 将 ArrayList 手动转换为 Array C#
问题描述
我已经完成了类List,它实现了一个数组列表数据结构。它看起来像这样:
class List
{
public int max;
public int last;
public int size;
int[] arr ;
public List(int n)
{
max = n;
last = -1;
arr = new int[max];
size = 1;
}
public void addItem(int item)
{
if (isFull())
{
Console.WriteLine("Memory overflow: item cannot be added to list.");
}
else
{
arr[++last] = item;
}
}
我可以以某种方式将 List 转换为数组吗?
解决方案
您可以向您的类添加一个公共方法,该方法返回该字段List
的副本:arr
public int[] ToArray() => arr.ToArray();
用法:
List list = new List(1);
list.addItem(1);
int[] array = list.ToArray();
推荐阅读
- python - 如何解决 django TypeError: __init__() got an unexpected keyword argument 'thread critical' 在 gitlab-ci 中的错误?
- c++ - 为什么 std::string 似乎做了 std::is_convertible 说不可能的事情?
- php - 从laravel中的外部api下载文件
- video-streaming - 使用 Locust 加载测试视频流
- ios - 如何在 Swift 5 中检查 3 个变量是否相等?
- opencv - 用于加载图像的 Mediapipe 自定义计算器
- reactjs - 对行进行排序后,Ag-grid 拖放不起作用
- mysql - JDBC ResultSet 是否支持分页?
- javascript - 自动面板问题中加载时的togle输入
- javascript - 为基于滚动位置的变量计算添加缓动