Friday 15 August 2014

c# - NullReferenceExceptionUnhandled -


I write a blackjack program but my problem is that when creating an object that contains a list of other objects, But when I make an item for the first time, the list is empty. I think this is the reason why I am getting this error below is my code where I initialize a player as an example of a hand in the player's constructor, but when I try the method player HD If I call, "Obvious reference is not set for an example of an object" error message;

  public class player {name of private string; Public hand player hand Public player () {} public player (string name) {this.Name = name; This.playerHand = New Hand (); } Public string name {get {return name; } Set {name = value; }} Public Zero Tech Card (Card Card) {playerHand.Hit (Card); } `  

`

  public class hands {public list & lt; Cards & gt; hand; Public hand () {hand = new list & lt; Cards & gt; (); } Public Entity Hand Values; `Public Zero Hits (Card Card) {Hands. Add (card); } Public int handvalue () {foreach (handheld card card) handValue + = (int) card.value; Return hand}} public class games {public game (IEnumerable & lt; string & gt; player name) {list & lt; Player & gt; Player = new list & lt; Player & gt; (); Players (name of string in player names) Add (new player (name)); Player Dealer = New Dealer (); Players.Add (dealer); Deck playing deck = new deck (); Deal (sports, player); Play (deck, player); DisplayResults (players); } Public Zero Deal (deck deck, list & gt; player & gt; player) {deck.Shuffle (); For (Int i = 1; i & lt; 3; i ++) Forac (player player player player). TechCard (DeckDial ()); }    

Your line is:

  Dealer = new dealer ();   

You did not show the code to us for dealer , but it is clear from the code that dealer: player note that Your default constructor for player never starts Player.playerHand . If the default constructor for dealer calls the default constructor for the player (and it is by default), then the playerHand will be < Dealer for code> null .

So, my guess is that playerHand.Hit (card); is giving you NullReferenceException when used for dealer , because you have never played the player. Player Player .

To fix this, just provide a launcher

  public hand playerhand = new hand (); Remove the line related to   

and the constructor player .

Finally, and it's a on one side , you have many public variables in your classes, you're "leaking" the variable, The name of the game, which can modify your class's consumer without restraint and dispel your anomalies.

No comments:

Post a Comment