0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#変数(値型)について

Last updated at Posted at 2020-06-01

C#変数(値型)
値型には2種類ある
・データと関連機能をカプセル化する構造体の型
・名前付き定数のセットによって、定義され、選択しまたは選択肢の組み合わせを表す列挙型。

組み込みの値型

⇒単純型とも呼ばれる組み込み値型が用意されています。
・整数数値型
・有働小数点数値型
・ブール値を表すbool
・Unicode UTF-16文字を表すchar

構造体の型
データおよび関連する機能をカプセル化できる値型。構造体型を定義するには、structキーワードを使用。
(つまり関連する項目を一つの塊にしたもの)

構造体はint型や文字列など型の違うモノでも一つの塊にできる。
(処理を定義することもできるのでクラスと似ている)

共通点 違い 構造体 クラス
インスタンス化して使用 オブジェクトの型 値型 参照型
使用する際にインスタンス化する クラスの継承 不可 可能
メソッドの定義 フィールドの初期化子の使用 不可 可能
フィールド(メンバ変数)だけではなく、メソッドを定義して処理を行う デフォルトコンストラクタ 不可 可能
引数ありコンストラクタの定義 デストラクタの定義 不可 可能
インスタンス化してフィールドの値を初期化する場合に使用
インターフェースの実装
インターフェースの実装(複数可)

構造体の定義
キーワードstructを使って以下のように定義。

	[修飾子]struct 構造体名
	{
		フィールド(メンバ変数);
	}

例えば2次元の座標を扱う場合は

	public struct Test
	{
		public int a;
		public int b;
	}

コンストラクタの定義
構造体では引数ありのコンストラクタの定義ができる
例:

public struct Test
{
	public int a;
	public int b;
	
	public Test(int a, int b){
		this.a = a;
		this.b = b;
	}
}

メソッドの定義
例:

public struct Sample
{
	public double d;
	
	public Sample(double dr){
		d = dr;
	}
	
	public double SampleA(double r){
		return 3.14 * r;
	}
	
	public double SampleArea(double r){
		return 3.14 * r * r;
	}
}

構造体を定義す売る際の注意点
・構造体のフィールドは初期化子を使用できない!
・引数なしのコンストラクタを定義できない!

参考資料:
・C#の絵本
・Microsoft Build
・Wikipedia

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?