簡體   English   中英

根據枚舉值打印二維數組

[英]print 2d array based on the enum values

首先,我有一個存儲 c ConsoleColor 值的枚舉,我想將一個二維數組打印到控制台,以便它顯示一個“#”而不是基於枚舉中設置的顏色的枚舉值,我一直在嘗試這樣做有一段時間了,但我無法得到任何幫助,我們將不勝感激。

這是我的代碼

public enum CandyCrushCandies
{
    JellyBean = ConsoleColor.Red, 
    Lozenge = ConsoleColor.DarkCyan, 
    LemonDrop = ConsoleColor.Yellow, 
    GumSquare = ConsoleColor.Green, 
    LollipopHead = ConsoleColor.Blue, 
    JujubeCluster = ConsoleColor.Magenta 
}

顯示到控制台的方法

  void DisplayCandyCrushCandies(CandyCrushCandies[,] playingField)
    {
        Array values = Enum.GetValues(typeof(CandyCrushCandies));
        Random rnd = new Random();
        CandyCrushCandies randomBar = (CandyCrushCandies)values.GetValue(rnd.Next(values.Length));

        string name = Enum.GetName(typeof(CandyCrushCandies), randomBar);
        var type = typeof(ConsoleColor);
      

        for (int row = 0; row < playingField.GetLength(0); row++)
        {
            for (int col = 0; col < playingField.GetLength(1); col++)
            {
                playingField[row, col] = (CandyCrushCandies)(ConsoleColor)type.GetProperty(name).GetValue(playingField[row, col]);
                Console.Write("# ", playingField[row, col]);
            }
            Console.WriteLine();
        }
    }

非常感謝先進

您的問題尚不清楚,但我假設您試圖詢問如何將 output着色#字符到控制台。 這應該不會太難,因為System.Console具有設置前景色(文本顏色)以及后續System.Console.Write/WriteLine調用正在打印的任何內容的背景色的屬性。

我發現您要打印“#”的行和列,其顏色由另一個數組確定:

void DisplayCandyCrushCandies(CandyCrushCandies[,] playingField)
{
   // I don't know what you want to do with this
   Array values = Enum.GetValues(typeof(CandyCrushCandies));
   Random rnd = new Random();
   CandyCrushCandies randomBar = (CandyCrushCandies)values.GetValue(rnd.Next(values.Length));

   string name = Enum.GetName(typeof(CandyCrushCandies), randomBar);
   var type = typeof(ConsoleColor);
   //


   for (int row = 0; row < playingField.GetLength(0); row++)
   {
       for (int col = 0; col < playingField.GetLength(1); col++)
       {
          //playingField[row, col] = (CandyCrushCandies)(ConsoleColor)type.GetProperty(name).GetValue(playingField[row, col]);

          Console.ForegroundColor = (ConsoleColor)playingField[row, col];
          Console.Write("# ");
       }
                Console.WriteLine();
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM