C# 将c数组添加到数组的
对c比较陌生,有点困惑 我有一个类,它检索2个值并将它们放在一个数组中,然后我希望将该数组添加到一个列表中 数组用作购买项目,列表用作购物篮C# 将c数组添加到数组的,c#,C#,对c比较陌生,有点困惑 我有一个类,它检索2个值并将它们放在一个数组中,然后我希望将该数组添加到一个列表中 数组用作购买项目,列表用作购物篮 public void Add(int Id , int Quantity ) { int[] buying = new int[] { Id, Quantity }; //AddTo(buying); List<int[]> arrayList = new List<int[]>(); array
public void Add(int Id , int Quantity )
{
int[] buying = new int[] { Id, Quantity };
//AddTo(buying);
List<int[]> arrayList = new List<int[]>();
arrayList.Add(buying);
}
我只是被困在如何添加到列表中,而不创建列表的新实例,从而丢失任何已添加的项
感谢您的帮助:那么您必须在其他地方拥有该列表的实例,将其置于函数之外:
List<int[]> arrayList = new List<int[]>();
public void Add(int Id , int Quantity )
{
int[] buying = new int[] { Id, Quantity };
//AddTo(buying);
arrayList.Add(buying);
}
最好使用,而不是int[]:
List<KeyValuePair<int, int>> arrayList = new List<KeyValuePair<int, int>>();
public void Add(int Id , int Quantity )
{
KeyValuePair<int, int> buying = new KeyValuePair<int, int>(Id, Quantity);
arrayList.Add(buying);
}
或者,如果您不需要特定的顺序,最好使用字典:
Dictionary<int, int> list = new Dictionary<int, int>();
public void Add(int Id , int Quantity )
{
list.add(Id, Quantity);
}
在课堂上定义你的列表
List<int[]> arrayList = new List<int[]>();
public void Add(int Id , int Quantity )
{
int[] buying = new int[] { Id, Quantity };
//AddTo(buying);
arrayList.Add(buying);
}
BTW,你应该考虑使用一个包含ID和数量属性的类。或者代替列表,你可以使用一个字典,关键字是ID,值是数量。
所以你的问题是当函数结束时,ARARYLIST不再是可访问的。解决此问题的一种方法是提供arrayList类作用域,另一种方法是将其发送到类或其他函数中声明的函数public void Add(List<int[]> list, int Id , int Quantity )
{
int[] buying = new int[] { Id, Quantity };
list.Add(buying);
}
除了其他答案之外。如果不想在类中特别使用列表,可以将列表作为参数传递给方法
public void Add(int id, int quantity, List<int[]> container)
{
int[] buying = new int[] { id, Quantity };
container.Add(buying);
}
双向
一,。将列表的引用传递到此函数
}
为什么要使用数组列表而不是列表列表?您需要将数组定义为类字段并添加到类字段中,或者在调用者中立即激发并传递它。似乎要购买的项目应该是对象而不是裸数组,特别是如果数组中的元素根据它们的位置具有特定的含义。初始数组是ok的,IMO…它是有限的,有2个元素,具有特定的用途指示。至少在开始的时候。C的新开发人员必须逐步完成开发并学习OPP首选的方法。只需将列表定义为类实例的一部分,而不是方法的一部分,并且无需每次重新初始化
public void Add(List<int[]> arrayList, int Id , int Quantity )
{
int[] buying = new int[] { Id, Quantity };
arrayList.Add(buying);
}
int[] buying = new int[] { Id, Quantity };
this.arrayList.Add(buying); }