我创建了一个类,岛,我在主类中创建了7个实例。每个实例都有一个in assigned,表示需要从每个容器中拾取多少个容器。
class Program
{
public static int[,] TEUlayer1 = new int[4, 4] { { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 } };
public static int[,] TEUlayer2 = new int[4, 4] { { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 0 } };
public static Island is1 = new Island(2);
public static Island is2 = new Island(3);
public static Island is3 = new Island(1);
public static Island is4 = new Island(4);
public static Island is5 = new Island(2);
public static Island is6 = new Island(2);
public static Island is7 = new Island(1);
static void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(TEUlayer1[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(TEUlayer2[i, j] + " ");
}
Console.WriteLine();
}
}
}
class Island
{
public int S8s4collection { get; set; }
public Island(int s8s)
{
s8s = S8s4collection;
}
}
可能值得忽略主要方法和TEUlayer1 / 2部分。这些代表了一艘小船上的一堆集装箱,但这与该问题无关。
我的问题是我可以创建一个循环或其他函数,它遍历岛类的每个实例(is1
,is2
...)并将与其关联的值附加到列表或数组等?
谢谢!
答案 0 :(得分:2)
为了能够遍历你的岛屿,你需要一群群岛。
这有效:
public class Program
{
public static int[,] TeuLayer1 = new int[4, 4] { { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 } };
public static int[,] TeuLayer2 = new int[4, 4] { { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 0 } };
public static List<Island> Islands = new List<Island> { new Island(2), new Island(3), new Island(1), new Island(4), new Island(2), new Island(2), new Island(1) };
static void Main(string[] args)
{
Program.PrintLayer(Program.TeuLayer1);
Program.PrintLayer(Program.TeuLayer2);
Program.PrintIsland(Program.Islands);
Console.ReadKey();
}
public class Island
{
public int S8s4collection { get; private set; }
public Island(int s8s)
{
S8s4collection = s8s;
}
}
private static void PrintIsland(IEnumerable<Island> islands)
{
var index = 0;
foreach (var island in islands)
{
Console.WriteLine("Island {0} has a 'S8s4collection' of: {1}", index, island.S8s4collection);
index++;
}
Console.WriteLine();
}
private static void PrintLayer(int[,] layer)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(layer[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
尽管一切都是静态的并不理想。哦,你的岛建设者错了。
输出:
答案 1 :(得分:1)
public static Island[] is = new Island[7];
public static Island is[1] = new Island(2);
...
然后如果你想循环
for(int i=0;i<is.Length;i++) {
is[i].DoSomething () ;
}