C#で選択(switch-case編)

プログラムを条件分岐する際には、if文の他にも、switch文があります。 式の値がパターンに一致するかどうか評価して、一致する場合はその実行内容を実行します。

目次

  1. Switch文
  2. 試してみた
    1. ビュー
    2. コード
    3. 動かしてみた

Switch文

switch文の書き方は概ね下記のような感じです。

switch (式)
{
    case パターン①:
        実行内容①;
        break;
    case パターン②:
        実行内容②;
        break;
    default:
        実行内容③;
        break;
}

式の値がパターン①に一致する場合は、実行内容①が実行されます。 式の値がパターン②に一致する場合は、実行内容②が実行されます。 式の値がどのパターンにも一致しない場合は、実行内容③が実行されます。 式の値がどのパターンにも一致せず、かつdefaultが指定されていない場合には、何も実行されません。

試してみた

クリックしたボタンに応じてテキストボックスの表示を変えるプログラムを作ってみました。

ビュー

グリッドにテキストボックスとボタンを並べました。

<Window x:Class="trial_switch.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:trial_switch"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="200">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <TextBlock Name="textblock" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Margin="5" />
        <Button Content="ぐー" Tag="G" Grid.Row="1" Grid.Column="0" Margin="5" Click="Button_Click" />
        <Button Content="ちょき" Tag="C" Grid.Row="1" Grid.Column="1" Margin="5" Click="Button_Click" />
        <Button Content="ぱー" Tag="P" Grid.Row="1" Grid.Column="2" Margin="5"  Click="Button_Click" />
    </Grid>
</Window>

ボタンにTagというプロパティを設定しました。 各ボタンがクリックされたときのイベントが、全て同じに設定されています。どのボタンをクリックしても同じメソッドが呼び出されるようにして、メソッドの側でどのボタンが押されたかを判断します。その際にTagプロパティを使用します。

コード

using System.Windows;
using System.Windows.Controls;

namespace trial_switch
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            switch (button.Tag.ToString())
            {
                case "G":
                    textblock.Text = "ぐー";
                    break;
                case "C":
                    textblock.Text = "ちょき";
                    break;
                case "P":
                    textblock.Text = "ぱー";
                    break;
                default:
                    break;
            }
        }
    }
}

ボタンをクリックされた際に呼び出される Button_Click(object sender, RoutedEventArgs e) メソッドのsenderという引数を、Button型のインスタンスにします。 そうすると、そのインスタンスのTagプロパティが参照できます。 switchの評価式にボタンのインスタンスのTagプロパティを設定して、Caseのパターンに合致した場合はテキストボックスを書き換えます。

動かしてみた

動かしてみました。 image0

公開日

広告