Bootstrap

C#从零开始学习(枚举和集合)(8)

枚举

枚举允许你处理一组合法值,enum要求这部分数据只能接受某些值

enum Suits{
	Diamonds;
	Clubs;
	Hearts,
	Spades,
}
Suits mySuit = Suits.Diamonds;

特点

  • 可以在变量定义中使用enum,就像时使用string,int 类似
  • 可以使用创建数组
  • 使用 == 比较enum值
  • 不能为enum创造新值

集合

要包含 using System.Collections.Generic;

List

List<Card> cards = new List<Card>();
cards.Add(xxx);

Dictionary

和c++中map相似

Dictionary <string,string> Foods = new Dictionary <string,string> ();
  • 增加
    Foods[“apple”] = “red”;
    Foods.Add(“apple”,“red”);
  • 查找
    string apple = Foods[“apple”];
  • 删除
    Foods.Remove(“apple”);
  • 得到键值
    foreach(string key in Foods.Keys){…}
  • 统计个数
    int howMany = Foods.Count;

Queue

队列,先进先出

Queue <string> myQueue = new Queue <string>();

myQueue.Enqueue("fisrt");
myQueue.Peek();

示例

存储鞋子(Shoes)

List的应用,提示用户增加或删除鞋子

  1. 为鞋子增加一个enum
  2. 增加Shoes类
  3. ShoeCloset类使用一个LIst< Shoe > 管理它的鞋子
  4. 增加入口点
    enum Style
    {
        Sneaker,
        Loafer,
        Sandal,
        Flipflop,
        Wingtip,
        Clog,
    }

class Shoe
    {
        public Style Style
        {
            get; private set;
        }
        public string Color
        {
            get; private set;
        }
        public Shoe(Style style, string color)
        {
            Style = style;
            Color = color;
        }
        public string Description
        {
            get { return $"A {Color} {Style}"; }
        }
    }

鞋子管理,拥有增加和删除的逻辑代码


namespace Shoes
{
    using System.Collections.Generic;

    class ShoeCloset
    {
        private readonly List<Shoe> shoes = new List<Shoe>();

        public void PrintShoes()
        {
            if (shoes.Count == 0)
            {
                Console.WriteLine("\nThe shoe closet is empty.");
            }
            else
            {
                Console.WriteLine("\nThe shoe closet contains:");
                int i = 1;
                foreach (Shoe shoe in shoes)
                {
                    Console.WriteLine($"Shoe #{i++}: {shoe.Description}");
                }
            }
        }

        public void AddShoe()
        {
            Console.WriteLine("\nAdd a shoe");
            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine($"Press {i} to add a {(Style)i}");
            }
            Console.Write("Enter a style: ");
            if (int.TryParse(Console.ReadKey().KeyChar.ToString(), out int style))
            {
                Console.Write("\nEnter the color: ");
                string color = Console.ReadLine();
                Shoe shoe = new Shoe((Style)style, color);
                shoes.Add(shoe);
            }
        }

        public void RemoveShoe()
        {
            Console.Write("\nEnter the number of the shoe to remove: ");
            if (int.TryParse(Console.ReadKey().KeyChar.ToString(), out int shoeNumber) &&
                (shoeNumber >= 1) && (shoeNumber <= shoes.Count))
            {
                Console.WriteLine($"\nRemoving {shoes[shoeNumber - 1].Description}");
                shoes.RemoveAt(shoeNumber - 1);
            }
        }
    }
}

鸭子比较(Duck)

构建程序使用List中的方法使得程序按照自己想要的方式排序

class Duck : IComparable<Duck>
    {
        public int Size { get; set; }
        public KindOfDuck Kind { get; set; }

        public int CompareTo(Duck duckToCompare)
        {
            if (this.Size > duckToCompare.Size)
                return 1;
            else if (this.Size < duckToCompare.Size)
                return -1;
            else
                return 0;
        }

        public override string ToString()
        {
            return $"A {Size} inch {Kind}";
        }
    }
    class DuckComparerByKind : IComparer<Duck>
    {
        public int Compare(Duck x, Duck y)
        {
            if (x.Kind < y.Kind)
                return -1;
            if (x.Kind > y.Kind)
                return 1;
            else
                return 0;
        }
    }

两叠牌(Two Decks)

允许在两叠牌之间移牌,左边的一叠牌有一些按钮,允许洗牌以及将它重置为52张牌,右边的一叠牌也有一些按钮,允许清空这碟牌
在这里插入图片描述

<Window x:Class="TwoDecksWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TwoDecksWPF"
        mc:Ignorable="d"
        Title="Two Decks" Height="450" Width="400" >

    <Window.Resources>
        <local:Deck x:Key="leftDeck"/>
        <local:Deck x:Key="rightDeck"/>
    </Window.Resources>

    <Grid>

        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition/>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Label x:Name="deck1Label" Content="Deck _1" 
               Margin="10,0,0,0" Target="{Binding ElementName=leftDeckListBox, Mode=OneWay}"/>
        <Label x:Name="deck2Label" Content="Deck _2" Grid.Column="1" Margin="10,0,0,0"
               Target="{Binding ElementName=rightDeckListBox, Mode=OneWay}"/>

        <ListBox x:Name="leftDeckListBox" Grid.Row="1" Margin="10,0,10,10"
            ItemsSource="{DynamicResource leftDeck}" 
            KeyDown="leftDeckListBox_KeyDown" />
        <ListBox x:Name="rightDeckListBox" Grid.Row="1" Grid.Column="1"
            Margin="10,0,10,10" ItemsSource="{DynamicResource rightDeck}" 
            KeyDown="rightDeckListBox_KeyDown" />
        
        <Button x:Name="shuffleLeftDeck" Content="_Shuffle" Grid.Row="2"
                Margin="10,0,10,10" Click="shuffleLeftDeck_Click" />
        <Button x:Name="clearRightDeck" Content="_Clear" Grid.Row="2" Grid.Column="1" 
                Margin="10,0,10,10" Click="clearRightDeck_Click" />
        <Button x:Name="resetLeftDeck" Content="_Reset" Grid.Row="3" 
                Margin="10,0,10,10" Click="resetLeftDeck_Click" />
        <Button x:Name="sortRightDeck" Content="Sor_t" Grid.Row="3" Grid.Column="1" 
                Margin="10,0,10,10" Click="sortRightDeck_Click" />
    </Grid>
</Window>

    enum Suits
    {
        Diamonds,
        Clubs,
        Hearts,
        Spades,
    }
    enum Values
    {
        Ace = 1,
        Two = 2,
        Three = 3,
        Four = 4,
        Five = 5,
        Six = 6,
        Seven = 7,
        Eight = 8,
        Nine = 9,
        Ten = 10,
        Jack = 11,
        Queen = 12,
        King = 13,
    }
    class Card
    {
        public Values Value { get; private set; }
        public Suits Suit { get; private set; }

        public Card(Values value, Suits suit)
        {
            this.Suit = suit;
            this.Value = value;
        }
        public string Name
        {
            get { return $"{Value} of {Suit}"; }
        }

        public override string ToString()
        {
            return Name;
        }

    }

至此,我们就学习完了第八章,然后让我们复习一下本章讲了什么

  • 学习了枚举的使用
  • 学习了C#中各种集合的使用
  • 学会了使用继承来编写集合的排序
;