我想遍历包含不同对象类型的ArrayList的ArrayList并将数据写入控制台。
我尝试使用IEnumerable和foreach循环。
//-------------------- Custom class Point --------------------
class Point
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public Point(double x, double y, double z) { this.X = x; this.Y = y; this.Z = z; }
}
//-------------------- Main program --------------------
class Program
{
static void Main(string[] args)
{
//ArrayList of different objects
ArrayList arrlist = new ArrayList{
new ArrayList { 1, "one" ,new Point(1.0,1.0,1.0)},
new ArrayList { "two", 2,new Point(2.0,2.0,2.0) },
new ArrayList { new Point(3.0,3.0,3.0), "three",3}
};
readData(arrlist);
Console.ReadLine();
}
//-------------------- readData() function definition --------------------
public static void readData(ArrayList arlst)
{
foreach (object obj in arlst)
{
foreach (object item in (IEnumerable)obj)
{
Console.WriteLine($"... {(IEnumerable)item.ToString()} ...");
}
}
}
}
我希望将输入的每个项目的实际值写到ArrayList中。
编辑:格式化
答案 0 :(得分:0)
这是您想要的输出吗?
... 1 ...
... one ...
... Point(1,1,1) ...
... two ...
... 2 ...
... Point(2,2,2) ...
... Point(3,3,3) ...
... three ...
... 3 ...
如果要打印点,则在Point类中需要这样的toString()方法
override public string ToString() { return $"Point({X},{Y},{Z})"; }
答案 1 :(得分:0)
//-------------------- Custom class Point --------------------
class Point
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public Point(double x, double y, double z) { this.X = x; this.Y = y; this.Z = z; }
}
//-------------------- Main program --------------------
class Program
{
static void Main(string[] args)
{
//ArrayList of different objects
ArrayList arrlist = new ArrayList{
new ArrayList { 1, "one" ,new Point(1.0,1.0,1.0)},
new ArrayList { "two", 2,new Point(2.0,2.0,2.0) },
new ArrayList { new Point(3.0,3.0,3.0), "three",3}
};
readData(arrlist);
Console.ReadLine();
}
//-------------------- readData() function definition --------------------
public static void readData(ArrayList arlst)
{
foreach (ArrayList l in arlst)
{
foreach (object item in l)
{
Console.WriteLine($"... {item.ToString()} ...");
}
}
}
}
答案 2 :(得分:0)
您可以将其用作数组列表以在数组列表上循环,有关示例,请参见注释:
public static void readData(ArrayList arlst)
{
foreach (object l in arlst)
{
// try to convert it to arrayList to keep
var data = l as ArrayList;safe!
if (data != null)
// it is an arrayList, loop on it an print values
foreach (object item in data)
Console.WriteLine($"... {item.ToString()} ...");
else
// print the value if it is not an array list
Console.WriteLine($"... {item.ToString()} ...");
}
}