(original) C # learning note 10--Defining Class Members 06--sample application 02--writing class libraries

Source: Internet
Author: User
Tags shuffle

10.6.2 Writing class Libraries

Classes and enumerations are included in a class library project Ch10cardlib. This project will contain 4. cs files, Card.cs contains the definition of the Card class, Deck.cs contains the definition of the Deck class, Suit.cs and Rank.cs files contain enumerations.

1. Create a new Class library project Ch10cardlib in the \chapter10 directory. Removes Class1.cs from the project.

2. Add: Suit.cs and Rank.cs files as modified below:

 using   System;  using   System.Collections.Generic;  using   System.Linq;  using   System.Text;  using   System.Threading.Tasks;  namespace   ch10cardlib{ public  enum   = 1  , deuce, three, four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King,}}  
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ch10cardlib{    publicenum  Suit    {        Club,        Diamond,        Heart,        Spade,    }}

3. Add the card class with the following code:

 Public classCard { Public ReadOnlySuit Suit;  Public ReadOnlyrank rank;  PublicCard (Suit newsuit, Rank newrank) {Suit=Newsuit; Rank=Newrank; }        PrivateCard () {} Public Override stringToString () {return " the"+ Rank +" of"+ Suit +"s"; }}

The overridden ToString () method writes the string representation of the stored enumeration value to the returned string, and the non-default constructor initializes the value of the suit and rank fields.

3. Add Deck Class

The deck class needs to use the following members defined by the class diagram:

Card[] Type of private field cards.

The public default constructor.

Public method Getcard (), which takes an int parameter, Cardnum, and returns an object of type card.

Public method Shuffle (), which returns void without parameters.

The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacech10cardlib{ Public classDeck {Privatecard[] cards;  PublicDeck () {cards=Newcard[ the];  for(intSuitval =0; Suitval <4; ++suitval) {                 for(intRankval =1; Rankval < -; ++rankval) {Cards[suitval* -+ Rankval-1] =NewCard ((Suit) Suitval, (Rank) rankval); }            }        }         PublicCard Getcard (intcardnum) {            if(Cardnum >=0&& Cardnum <=Wuyi)            {                returnCards[cardnum]; }            Else            {                Throw(NewSystem.ArgumentOutOfRangeException ("Cardnum", Cardnum,"Value must be between 0 and Wuyi.")); }        }         Public voidShuffle () {card[] Newdeck=Newcard[ the]; BOOL[] assigned =New BOOL[ the]; Random Sourcegen=NewRandom ();  for(inti =0; I < the; ++i) {intDestcard =0; BOOLFoundcard =false;  while(false==Foundcard) {Destcard= Sourcegen.next ( the); if(false==Assigned[destcard]) {Foundcard=true; }} Assigned[destcard]=true; Newdeck[destcard]=Cards[i]; } Newdeck.copyto (Cards,0); }    }}

Shuffle () method. This method creates a temporary array of cards and randomly copies the cards from the existing cards array into the array. The body of this function is a loop from 0~51, where each loop uses an instance of the System.Random class in the. NET framework to generate a random number between 0~51. After the instantiation, the object of this class uses the method next (X) to generate a random number between 0~x. Once you have a random number, you can use it as an index to the card object in the temporary array to copy the cards in the cards array.

To record the assigned poker, we also have an array of bool variables, specifying the values in the array as true when each card is copied. When generating a random number, check the array to see if a card has been copied to the location specified by the random number in the temporary array, and if so, another random number will be generated.

This is not the most efficient way to accomplish this task, because many random numbers that are generated may not find an empty location to copy poker. However, it can still accomplish the task, and it is simple because C # code executes very quickly and we are almost unaware of the delay.

The last line of this method uses the CopyTo () method of the System.Array class (used when creating the array) to copy each card in the Newdeck back to cards . In other words, instead of creating a new instance, we use the same set of Card objects in the same cards object. if you use cards = Newdeck Instead, the object instance referenced by the cards is replaced with another object. If the code elsewhere still retains a reference to the original cards instance, there will be a problem -no shuffling.

At this point, the class library code is completed.

(original) C # learning note 10--Defining Class Members 06--sample application 02--writing class libraries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.