Programming」カテゴリーアーカイブ

プログラミング全般に関するカテゴリーです。

C#で配列のサイズを調べる方法

配列のサイズを調べる方法

Lengthを使って配列のサイズを調べることができます。

int[] array1 = new int[]{ 1, 2, 3, 4, 5 };

Debug.Log($"Length = {array1.Length}");

実行結果

Length = 5

ジャグ配列の場合

int[][] array2 = new int[][]{
  new int[] { 1, 2, 3 },
  new int[] { 4, 5, 6, 7 }
};

Debug.Log($"Length = {array2.Length}");
Debug.Log($"Length = {array2[0].Length}");
Debug.Log($"Length = {array2[1].Length}");

実行結果

Length = 2
Length = 3
Length = 4

多次元配列の場合

多次元配列の場合はGetLengthを使って調べられます。

int[,] array3 = new int[,]{
  { 1, 2, 3 },
  { 4, 5, 6 }
};

Debug.Log($"Length = {array3.GetLength(0)}");
Debug.Log($"Length = {array3.GetLength(1)}");

実行結果

Length = 2
Length = 3

C#でoperator[]のオーバーロード

operator[]のオーバーロード

C#で自作クラスにoperator[]を追加したい場合は次のような感じで実装できます。

class Example
{
  int[] _ar = new int[10];                                                                       
  
  public int this[int i]
  {
    get => _ar[i];                                                                        
    set => _ar[i] = value;                                                                       
  }
}

Exampleクラスを使う方は次のような感じです。

var example = new Example();

example[2] = 345;

Debug.Log($"example[2] = {example[2]}");

実行結果

example[2] = 345

多次元配列

多次元配列のような感じで使いたい場合も次のような感じで実装できます。

class Example2
{
  int[,] _ar = new int[10, 10];

  public int this[int i, int j]
  {
    get => _ar[i, j];
    set => _ar[i, j] = value;
  }
}

Compiler Error CS0720

static classoperator[]を実装しようとするとCS0720というエラーになるようです。気を付けてください。

/* static */ class Example3
{
  public int this[int i]
  {
    get => 0;
  }
}

※配列の範囲外にアクセスしようとするとIndexOutOfRangeExceptionという例外が発生します。実際に使う場合は注意してください。

Unityで継承元のStartやUpdateを呼び出す方法

Unityでクラスの継承を利用する場合、単にvoid Start()void Update()と書くと継承元の実装は呼び出されない形になります。

サンプル1

public class Example1 : MonoBehaviour
{
  void Start()
  {
    Debug.Log("Start1");
  }
  void Update()
  {
    Debug.Log("Update1");
  }
}

public class Example2 : Example1
{
  void Start()
  {
    Debug.Log("Start2");
  }
  void Update()
  {
    Debug.Log("Update2");
  }
}

Example2の実行結果

Start2
Update2
Update2
Update2
...

このExample2から継承元Example1StartUpdateを呼び出したい場合はvirtual protectedoverride protectedを使って次のような感じで実装できるみたいです。

サンプル2

public class Example1 : MonoBehaviour
{
  virtual protected void Start()
  {
    Debug.Log("Start1");
  }
  virtual protected void Update()
  {
    Debug.Log("Update1");
  }
}

public class Example2 : Example1
{
  override protected void Start()
  {
    base.Start();
    Debug.Log("Start2");
  }
  override protected void Update()
  {
    base.Update();
    Debug.Log("Update2");
  }
}

Example2の実行結果

Start1
Start2
Update1
Update2
Update1
Update2
Update1
Update2
...

base.を使った継承元メソッドの呼び出しはStartUpdate以外でも使えます。必要な場所で試してみてください。