Visual Studioで作る「Studentクラス」入門チュートリアル

広告

はじめに

前回の記事「オブジェクト指向って、最初は分からなくても大丈夫です」では、オブジェクト指向をいきなり難しい言葉で覚えるのではなく、「データ」と「処理」をひとまとめにする考え方として説明しました。

今回は、それをVisual Studioで実際に入力しながら確認していきます。最初から完成コードをすべて入力するのではなく、「今、何を追加したのか」「追加したことで、何が便利になったのか」を1つずつ確認します。

1. Console.WriteLineだけで表示する
2. nameとscoreを変数にする
3. Studentクラスを作る
4. new Student()で1人作る
5. 2人目、3人目を作る
6. ShowScoreメソッドを追加する
7. Student[] 配列に入れる
8. foreach文で順番に表示する
9. 最後にStudent.csへファイルを分ける

この順番で進めると、クラスやオブジェクト指向を急に難しく感じにくくなります。

今回作るプログラム

生徒の名前と点数を表示するプログラムを作ります。最終的な実行結果は次のとおりです。

田中さんの点数は80点です。
佐藤さんの点数は95点です。
鈴木さんの点数は70点です。

ただの表示から始め、変数、クラス、インスタンス、メソッド、配列、foreach文、別ファイル化へ進みます。

Visual Studioで新しいプロジェクトを作る

Visual Studioを起動し、次の手順で新しいプロジェクトを作ります。

  1. 「新しいプロジェクトの作成」をクリックする
  2. 「コンソール アプリ」を選ぶ
  3. 言語がC#になっていることを確認する
  4. プロジェクト名に「StudentClassTutorial」と入力する
  5. 「作成」をクリックする

入力順1:まずは普通に表示する

最初はクラスを使わず、Program.csに文字を表示するコードを書きます。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("田中さんの点数は80点です。");
        }
    }
}

ここでは、まずVisual Studioで入力して実行できることを確認します。

入力順2:名前と点数を変数にする

次に、名前と点数を別々の変数にします。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string name = "田中";
            int score = 80;

            Console.WriteLine($"{name}さんの点数は{score}点です。");
        }
    }
}

namescoreを使うことで、名前と点数を別々のデータとして扱えるようになりました。ここで、名前と点数はセットで扱いたいデータだと意識します。

入力順3:Studentクラスを作る

Studentクラスを設計図として表し、名前と点数を持つ複数の生徒を作るイメージ
Studentクラスは、生徒を作るための設計図です。

次に、Studentクラスを作ります。最初はProgram.csの下にそのまま書いて大丈夫です。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string name = "田中";
            int score = 80;

            Console.WriteLine($"{name}さんの点数は{score}点です。");
        }
    }

    class Student
    {
        public string Name;
        public int Score;
    }
}

Studentは、生徒を表す設計図です。Nameは名前、Scoreは点数を表します。この時点では、まだ実際の生徒は作っていません。

入力順4:new Student()で1人作る

先ほどのnamescoreは使わず、Studentを使う形に変えます。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student();

            student1.Name = "田中";
            student1.Score = 80;

            Console.WriteLine($"{student1.Name}さんの点数は{student1.Score}点です。");
        }
    }

    class Student
    {
        public string Name;
        public int Score;
    }
}

Student student1は「Student型の変数student1を用意する」、new Student()は「新しいStudentを作る」という意味です。

クラスとインスタンスの違い

1つのStudentクラスから異なるデータを持つ3人のインスタンスを作るイメージ
同じStudentクラスから、別々のデータを持つインスタンスを作れます。

class Studentは設計図です。一方、new Student()で作られたstudent1は、実際に使える生徒です。このように、クラスから作られた実物をインスタンスと呼びます。

クラス       → 設計図
インスタンス → 実物

入力順5:2人目、3人目を作る

同じStudentクラスから、2人目と3人目も作ります。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student();
            student1.Name = "田中";
            student1.Score = 80;

            Student student2 = new Student();
            student2.Name = "佐藤";
            student2.Score = 95;

            Student student3 = new Student();
            student3.Name = "鈴木";
            student3.Score = 70;

            Console.WriteLine($"{student1.Name}さんの点数は{student1.Score}点です。");
            Console.WriteLine($"{student2.Name}さんの点数は{student2.Score}点です。");
            Console.WriteLine($"{student3.Name}さんの点数は{student3.Score}点です。");
        }
    }

    class Student
    {
        public string Name;
        public int Score;
    }
}

student1student2student3は別々の生徒です。同じ設計図を使っていても、それぞれ異なる名前と点数を持てます。

入力順6:ShowScoreメソッドを追加する

点数を表示する処理は生徒に関係する処理なので、Studentクラスの中へ移します。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student();
            student1.Name = "田中";
            student1.Score = 80;

            Student student2 = new Student();
            student2.Name = "佐藤";
            student2.Score = 95;

            Student student3 = new Student();
            student3.Name = "鈴木";
            student3.Score = 70;

            student1.ShowScore();
            student2.ShowScore();
            student3.ShowScore();
        }
    }

    class Student
    {
        public string Name;
        public int Score;

        public void ShowScore()
        {
            Console.WriteLine($"{Name}さんの点数は{Score}点です。");
        }
    }
}

ShowScoreは「点数を表示する」という意味のメソッドです。データだけでなく、データに関係する処理もStudentの中に入りました。

Console.WriteLineではなくShowScoreを使う理由

student1.ShowScore();と書くことで、点数を表示する処理をStudentクラスの中にまとめられます。表示形式を変える場合も、ShowScoreの中だけを直せばよくなります。

public void ShowScore()
{
    Console.WriteLine($"名前: {Name} / 点数: {Score}");
}

このように、関係するデータと処理を1つにまとめると、あとで変更しやすくなります。

入力順7:Studentの配列に入れる

3人の生徒をStudent型の配列に入れます。

// 省略しない書き方
Student[] students = new Student[] { student1, student2, student3 };

// 左辺でStudent[]型が分かるため、次のようにnew Student[]を省略することもできる
// Student[] students = { student1, student2, student3 };

int[]が整数を入れる配列なのに対し、Student[]はStudentを入れる配列です。

students[0] → 田中さん
students[1] → 佐藤さん
students[2] → 鈴木さん

入力順8:foreach文で順番に表示する

配列に入れた生徒を、foreach文で1人ずつ取り出して表示します。

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student();
            student1.Name = "田中";
            student1.Score = 80;

            Student student2 = new Student();
            student2.Name = "佐藤";
            student2.Score = 95;

            Student student3 = new Student();
            student3.Name = "鈴木";
            student3.Score = 70;

            Student[] students = new Student[] { student1, student2, student3 };

            foreach (var student in students)
            {
                student.ShowScore();
            }
        }
    }

    class Student
    {
        public string Name;
        public int Score;

        public void ShowScore()
        {
            Console.WriteLine($"{Name}さんの点数は{Score}点です。");
        }
    }
}

foreach (var student in students)は、studentsの中からStudentを1人ずつ取り出し、studentという変数に入れるという意味です。

for文で書く場合

配列の番号を意識して復習したい場合は、for文でも書けます。

for (var i = 0; i < students.Length; i++)
{
    students[i].ShowScore();
}

今回のように番号を直接使わない場合は、foreachの方が自然に読めます。

入力順9:Studentクラスを別ファイルに分ける

ここまでは全体を見やすくするため、Program.csの中にStudentクラスも書きました。慣れてきたら、StudentクラスをStudent.csへ分けます。

Visual Studioでプロジェクトを右クリックし、「追加」→「クラス」を選び、ファイル名をStudent.csにします。

Program.cs

using System;

namespace StudentClassTutorial
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student();
            student1.Name = "田中";
            student1.Score = 80;

            Student student2 = new Student();
            student2.Name = "佐藤";
            student2.Score = 95;

            Student student3 = new Student();
            student3.Name = "鈴木";
            student3.Score = 70;

            Student[] students = new Student[] { student1, student2, student3 };

            foreach (var student in students)
            {
                student.ShowScore();
            }
        }
    }
}

Student.cs

using System;

namespace StudentClassTutorial
{
    class Student
    {
        public string Name;
        public int Score;

        public void ShowScore()
        {
            Console.WriteLine($"{Name}さんの点数は{Score}点です。");
        }
    }
}

2つのファイルでnamespace StudentClassTutorialを同じにしておけば、Program.csからStudentを使えます。

なぜ最初からファイルを分けないのか

最初は1つのファイルに書くことで、ProgramとStudentの関係を同じ画面で確認できます。クラスの役割を理解してから別ファイルへ移すと、「コードが長くなったので整理する」という理由も実感できます。

今回のまとめ

  • class Studentは、生徒を表す設計図
  • new Student()で、実際に使える生徒を作る
  • NameScoreは、生徒が持つデータ
  • ShowScore()は、生徒ができる処理
  • Student[]を使うと、複数の生徒を配列で管理できる
  • foreach文やfor文で、複数の生徒を順番に処理できる
  • 理解できたら、StudentクラスをStudent.csへ分ける

オブジェクト指向は、最初から難しい言葉で覚える必要はありません。まずは、関係するデータと処理を、意味のある単位でまとめるという感覚を持つことが大切です。今回の例では、名前と点数というデータと、点数を表示する処理をStudentという単位にまとめました。これがオブジェクト指向の第一歩です。

訪問数 9 回, 今日の訪問数 9回

広告

C#

Posted by hidepon