4.8.txt

来自「《Microsoft Visual C# .NET 2003开发技巧大全》源代码」· 文本 代码 · 共 77 行

TXT
77
字号
Listing 4.8 Implementing a Strongly Typed Collection by Deriving from
CollectionBase and Storing Card Objects
using System;
using System.Collections;
namespace _13_CardCollection
{
//
// Card implementation from Listing 4.7 here
//
public class CardHand : CollectionBase
{
public CardHand()
{
}
public override string ToString()
{
string ret = “”;
// print out name of each card in hand
foreach( Card c in base.InnerList )
ret += c.ToString() + “\n”;
return ret;
}
public void GenerateRandomHand( int numCards )
{
// initialize random number generator using tick count
Random rand = new Random( (int)DateTime.Now.Ticks );
// copy to array and sort
ArrayList sortedCards = (ArrayList) base.InnerList.Clone();
sortedCards.Sort( new Card() );
for( int i = 0; i < numCards; i++ )
{
Card newCard;
do
{
int val = rand.Next( 2, 15 );
int suit = rand.Next( 1, 4 );
// create new random card
newCard = new Card( (CardValues) val, (CardSuits) suit );
// make sure card doesn’t already exist
// by searching current hand
} while( sortedCards.BinarySearch(newCard, newCard ) > 0);
// add to sorted cards array
sortedCards.Add( newCard );
Add( newCard );
// resort the sortedCards collection
sortedCards.Sort( new Card() );
}
}
public int Add( Card value )
{
// add to base class list
return base.InnerList.Add( (object)value );
}
public void Remove( Card value )
{
// remove from base class list
base.InnerList.Remove( value );
}
public void Sort()
{
base.InnerList.Sort( new Card() );
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
CardHand hand = new CardHand();
hand.GenerateRandomHand( 5 );
Console.WriteLine( “Random Hand\n” + hand.ToString() );
hand.Sort();
Console.WriteLine( “\nSorted Hand\n” + hand.ToString() );
Console.WriteLine( “Total of {0} cards”, hand.Count );
}
}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?