「C#」親クラスを継承するサンプル

書式
1.親クラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class 親クラス
{
  処理コード;
}
class 親クラス {   処理コード; }
class 親クラス
{
  処理コード;
}

2.親クラスの機能を継承して子クラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class 子クラス : 親クラス
{
  子クラスの処理コード;
}
class 子クラス : 親クラス {   子クラスの処理コード; }
class 子クラス : 親クラス
{
  子クラスの処理コード;
}

親クラスを継承した子クラスは、親クラスの機能を使用することができます。

3.子クラスのインスタンスを作成
子クラス名 インスタンス名 = new 子クラス名();
インスタンス名.親クラスのメンバー変数名 = 値

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.IO;
namespace ConsoleApplicationSample
{
class Program
{
//親クラス
class People
{
public string name;
public int age;
}
// 親クラスPeopleを継承
class Student : People 
{
public string grade;
}
static void Main(string[] args)
{
// 子クラスであるStudentクラスのインスタンスを作成
Student st = new Student();
st.name = "山田 太郎";
st.age = 25;
st.grade = "東京大学";
Console.WriteLine("名前: "+st.name + " 年齢: " + st.age + " 大学: " + st.grade);
Console.ReadKey();
}
}
}
using System; using System.IO; namespace ConsoleApplicationSample { class Program { //親クラス class People { public string name; public int age; } // 親クラスPeopleを継承 class Student : People  { public string grade; } static void Main(string[] args) { // 子クラスであるStudentクラスのインスタンスを作成 Student st = new Student(); st.name = "山田 太郎"; st.age = 25; st.grade = "東京大学"; Console.WriteLine("名前: "+st.name + " 年齢: " + st.age + " 大学: " + st.grade); Console.ReadKey(); } } }
using System;
using System.IO;

namespace ConsoleApplicationSample
{
    class Program
    {
        //親クラス 
        class People
        {
            public string name;
            public int age;
        }
        // 親クラスPeopleを継承
        class Student : People 
        {
            public string grade;
        }

        static void Main(string[] args)
        {
            // 子クラスであるStudentクラスのインスタンスを作成
            Student st = new Student();
            st.name = "山田 太郎";
            st.age = 25;
            st.grade = "東京大学";

            Console.WriteLine("名前: "+st.name + " 年齢: " + st.age + " 大学: " + st.grade);
            Console.ReadKey();
        }
    }
}

実行結果
名前: 山田 太郎 年齢: 25 大学: 東京大学

C#

Posted by arkgame