我试图弄清楚如何使用一个数字数组的值来初始化第二个对象数组。这可能不是在真实程序中执行此类操作的最有效方法,但我只是想了解如何在两个不同的数组之间创建关系。第一个数组只是一个随机生成的数组,其值为0,1或2.第二个数组是一个Occupant对象数组。每个占用者的占用者id都是0,1或2.我试图通过复制第一个数组的值然后根据占用者id初始化第二个数组来生成第二个占用者数组。我没有尝试过任何东西都会编译,除了写一百万if语句之外,我自己也想不出任何其他东西。当然必须有一个我想念的简单解决方案。我们将非常感谢您提供的任何帮助。
仅供参考:乘客是基类,从中派生出三个类,每个类都有一个唯一的ID号。
static public class Board
{
static public Occupant[,] board = BoardGen();
static private Occupant[,] BoardGen()
{
Random myRandom = new Random();
int[,] setup = new int[10, 10];
for (int i = 0; i < setup.GetLength(0); i++)
{
for (int j = 0; j < setup.GetLength(1); j++)
setup[i, j] = myRandom.Next(0, 3);
}
Occupant[,] populate = new Occupant[10,10];
// How to link setup to populate using the number to choose an occupant based on it's id number?
return populate;
}
}
}
我建议填写第二个表和第一个,甚至更好,完全忘记第一个表:
static private Occupant[,] BoardGen()
{
Random myRandom = new Random();
// Not needed
// int[,] setup = new int[10, 10];
Occupant[,] populate = new Occupant[10, 10];
for (int i = 0; i < populate .GetLength(0); i++)
{
for (int j = 0; j < populate .GetLength(1); j++)
{
int randomSetup = myRandom.Next(0, 3);
switch (randomSetup)
{
case 0:
populate[i, j] = new Occupant_0(); // Derived Class with id=0
break;
case 1:
populate[i, j] = new Occupant_1(); // Derived Class with id=1
break;
case 2:
populate[i, j] = new Occupant_2(); // Derived Class with id=2
break;
default:
break;
}
}
}
return populate;
}
abstract class Master
{
public abstract int Id { get; }
}
class A : Master
{
public override int Id => 1;
}
class B : Master
{
public override int Id => 2;
}
class C : Master
{
public override int Id => 3;
}
Type[] types = new Type[] { typeof(A), typeof(B), typeof(C) };
int[] yourIds = new int[100];
Master[] generated = new Master[yourIds.Length];
for (int i = 0; i < yourIds.Length; i++)
{
generated[i] = (Master)Activator.CreateInstance(types[yourIds[i] - 1]);
}
我无法完全理解你的问题,但这种逻辑应该适合你的情况。
关键是你可以使用System.Activator
和System.Type
在运行时创建一个实例。