C#错误:使用未分配的局部变量

前端之家收集整理的这篇文章主要介绍了C#错误:使用未分配的局部变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
错误是在for循环中引起的:
  1. for (i = 0; i < hand.Length; i++)
  2. {
  3. Console.WriteLine(hand[i]);
  4. }

我试图存储值,以便以后显示它们.写作线可以帮助我确保代码实际上按照我的意图运行.

其余代码供参考:
*编辑:添加了一行代码

  1. enum house //variable type for the card type
  2. {
  3. Spades,Hearts,Clubs,Diamonds
  4. }
  5.  
  6. enum cards //variable type for the cards
  7. {
  8. Joker,Ace,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King
  9. }
  10.  
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15.  
  16. Random rnd;
  17. Random rnd2;
  18.  
  19. int i;
  20. int random;
  21. int random2;
  22.  
  23. String[] hand;
  24.  
  25. house randomhouse;
  26. cards randomcard;
  27.  
  28. //all declared variables
  29.  
  30. Console.WriteLine("Your hand is made up of :");
  31.  
  32. for (i = 0; i <= 6; i++)//does everything in the {} until i is equal to 6
  33. {
  34.  
  35. rnd2 = new Random();
  36. random2 = rnd2.Next(0,14);
  37. randomcard = (cards)random2; //selecting a random card from joker to king
  38.  
  39. if (randomcard > (int)cards.Joker) //if the random card isn't a joker
  40. {
  41. rnd = new Random();
  42. random = rnd.Next(0,4);
  43. randomhouse = (house)random;//selects a random card type
  44.  
  45. Console.WriteLine(randomcard + " of " + randomhouse); //outputs the name of the card
  46. System.Threading.Thread.Sleep(1000);//wait 1 second before getting the new card
  47. }
  48.  
  49. else
  50. {
  51. Console.WriteLine(randomcard);//outputs "Joker"
  52. System.Threading.Thread.Sleep(1000);//wait 1 second before getting the new card
  53. }
  54.  
  55. hand = new String[i];//making a new array value for every loop
  56. hand[i] = randomcard.ToString();//adding randomcard to the array*
  57.  
  58. }
  59.  
  60. Console.Clear();
  61.  
  62. for (i = 0; i < hand.Length; i++)
  63. {
  64. Console.WriteLine(hand[i]);
  65. }
  66.  
  67. Console.ReadKey();
  68. }
  69. }

解决方法

编译器永远无法确定手是否已实际初始化.您应该先将其初始化,或将其设置为null,以便绕过此编译器检查.

所以你可以这样做,但事实上这是不好的做法!更改代码时,最终可能会出现NullReferenceException!

  1. String[] hand = null;

你知道你的代码实际上并不起作用,因为你最终会得到一个数组.我想你的意思是:

  1. hand = new String[6];
  2.  
  3. ...
  4.  
  5. hand[i] = theValue;

猜你在找的C#相关文章