C#の構造体は、C/C++の構造体とは全く異なるものです。
構造体(structure)は、どちらかというとクラスに近いものです。しかし、決定的に違う
ことがいくつかあります。クラスは参照型ですが、構造体は値型です。
構造体は、構造体やクラスを継承することはできません。また、継承元になることもできません。
構造体は、次のように定義します。
struct 構造体名
{
...
}
...に構造体のメンバを定義します。構造体のメンバはクラスと同様のメンバを定義できます。(引数無しコンストラクタとデストラクタをのぞく)では、簡単な例を見てみましょう。
// struct01.cs
using System;
struct MyStruct
{
int struct_x;
int[] ar;
public int Show()
{
Console.WriteLine("struct_x = {0}", struct_x);
return 0;
}
public int x
{
get
{
return struct_x;
}
set
{
struct_x = value;
}
}
public int this[int n]
{
get
{
return ar[n];
}
set
{
ar[n] = value;
}
}
public MyStruct(int a)
{
ar = new int[a];
struct_x = 0;
}
}
class struct01
{
public static void Main()
{
// 独自のコンストラクタの使用
MyStruct ms = new MyStruct(5);
// プロパティの使用
ms.x = 10;
Console.WriteLine("struct_x = {0}", ms.x);
// メソッドの使用
ms.Show();
// インデクサの使用
for (int i = 0; i < 5; i++)
ms[i] = i * 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("ms[{0}] = {1}", i, ms[i]);
}
}
}
構造体MyStructには、privateなインスタンスフィールド、publicなメソッド、
プロパティ、インデクサをメンバに持っています。また、引数付きコンストラクタも
あります。Mainメソッドでは、MyStruct構造体のインスタンスを使って、プロパティやメソッドや インデクサを利用しています。使い方はクラスと全く同じですね。
実行結果は、次のようになります。
Update 26/Sep/2006 By Y.Kumei