【发布时间】:2020-12-04 15:52:37
【问题描述】:
有一个数组列表,它由泛型列表组成,泛型列表的元素是类变量。我怎样才能打印整个arrayList?我必须使用数组列表、通用列表和一个类。逻辑类似于 Array List[Generic Lists[Classes]]。
namespace temp
{
internal class tempClass
{
public string Name;
public int Number;
}
internal class Program
{
private static void Main(string[] args)
{
string[] Names = { "a", "b", "c", "d", "e", "f","g", "h", "i", "j", "k", "l", "m","n", "o", "p", "q", "r", "s", "t", "u","v", "w", "x", "y", "z", "z2", "z3" };
int[] Number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,20, 21, 22, 23, 24, 25, 26, 27, 28 };
ArrayList arrayList = new ArrayList();
int counter = 0;
List<tempClass> genericList;
tempClass ClassExample;
for (int i = 0; i < Names.Length;)
{
genericList = new List<tempClass>();
int elementCount = (int)Math.Pow(2, counter);
for (int j = 0; j < elementCount; j++)
{
ClassExample = new tempClass();
ClassExample.Name = Names[i];
ClassExample.Number = Number[i];
genericList.Add(ClassExample);
i++;
if (i == Names.Length) break;
}
arrayList.Add(genericList);
counter++;
}
Console.Read();
}
}
} ```
【问题讨论】:
-
仅供参考
ArrayList是 .Net 1 在添加泛型之前的遗留物。我建议根本不使用它,而是使用List<List<tempClass>>。基本上,如果您想获取ArrayList中的内容,您需要知道类型,您可以执行foreach(List<tempClass> x in arrayList)但是您可以将任何内容添加到ArrayList,因此可能会遇到转换错误,这就是为什么您不应该使用它。 -
根本没有理由使用 ArrayList。另外,您到底需要打印什么?这只是主循环中的一个简单循环。
-
对于
ArrayList,请注意the documentation“备注”部分下蓝色框中的文字:“我们不建议您将ArrayList类用于新的开发。相反,我们建议您使用通用的List<T>类。" -
List<tempClass> tempClasses = Enumerable.Range(0, Names.Length).Select(index => new tempClass {Name = Names[index], Number = Number[index]}).ToList();
标签: c# class arraylist generic-list