如何在C#中创建char,int,int的bool 3D数组

时间:2017-11-07 20:04:03

标签: c# arrays

我正在尝试创建一个包含char,int和int的bool 3d 数组,例如

Table['a', 0, 5] = false;

Table['b', 1, 4] = true;

我创建 2d 但无法创建 3d

var cells = new bool[word.Length, word.Length];

for (int i = 0; i < word.Length; i++)
{
  for (int j = 0; j < word.Length; j++)
  {
     cells[i, j] = false; // what to write here 
  }
}

2 个答案:

答案 0 :(得分:3)

您可以使用元组和bool的字典,如下所示:

var t = new Dictionary<Tuple<char, int, int>, bool>();

t.Add(Tuple.Create<char, int, int>('a', 0, 5), false);
t.Add(Tuple.Create<char, int, int>('b', 1, 4), true);

// Prints false
Console.WriteLine("a, 0, 5 = {0}", t[Tuple.Create<char, int, int>('a', 0, 5)]);
// Prints true
Console.WriteLine("b, 1, 4 = {0}", t[Tuple.Create<char, int, int>('b', 1, 4)]);

答案 1 :(得分:2)

如果您坚持 3D阵列,我建议这样的事情:

 // ['a'..'z', 0..word.Length - 1, 0..word.Length - 1] bool array 
 // (first index is not zero-based)
 bool[,,]cells = (bool[,,]) Array.CreateInstance(
   typeof(bool),                               // Array items type
   new int[] { 26, word.Length, word.Length }, // Sizes
   new int[] { 'a', 0, 0 });                   // Lower bounds 

 ...

 // Single item addressing
 cells['b', 1, 4] = true;

 ...

 // Loop over all the array's items
 for (int i = cells.GetLowerBound(0); i <= cells.GetUpperBound(0); ++i)
   for (int j = cells.GetLowerBound(1); j <= cells.GetUpperBound(1); ++j)
     for (int k = cells.GetLowerBound(2); k <= cells.GetUpperBound(2); ++k) { 
       // ... cells[i, j, k] ...
     }

您似乎想要从'a'开始第一个索引,而不是从0开始,这就是我提供复杂调用的原因。请注意,您不必将数组的项初始化为false

https://msdn.microsoft.com/en-us/library/x836773a(v=vs.110).aspx

了解详情