2009年12月6日日曜日

構造体をnewキーワードでインスタンス化し既定のコンストラクタ、既定ではないコンストラクタを呼び出してみる。

using System;

// 構造体を定義
struct Sample
{
    public int age;
    public string name;

    // パラメータ付きのコンストラクタ
    public Sample(int a, string s)
    {
        age = a;
        name = s;
    }
}
class MainClass
{
    static void Main()
    {
        // 既定のコンストラクタを呼び出す
        Sample s = new Sample();

        // 出力値:(int型の既定値)0
        Console.WriteLine(s.age);
        // 出力値:(string型の既定値null)
        Console.WriteLine(s.name);

        // コンストラクタを呼び出す
        Sample s1 = new Sample(100, "Kamimura");

        // 出力値:100
        Console.WriteLine(s1.age);
        // 出力値:Kamimura
        Console.WriteLine(s1.name);
    }
}

0 コメント:

コメントを投稿