C#」カテゴリーアーカイブ

プログラミング言語「C#」に関するカテゴリーです。

C#の自作クラスでforeachを使う

C#の自作クラスでforeachを使いたい場合はGetEnumeratorというメソッドを追加してみれば良いようです。

public class Example : MonoBehaviour
{
  public IEnumerator<string> GetEnumerator()
  {
    yield return "A";
    yield return "B";
    yield return "C";
  }
}

こんな感じにすると、

Example example = new Example();

foreach(string s in example) {
  Debug.log(s);
}

のように使えます。

リンク

How to use foreach keyword on custom Objects in C# – Stack Overflow
https://stackoverflow.com/questions/348964/how-to-use-foreach-keyword-on-custom-objects-in-c-sharp

C#で配列や構造体の初期化方法

C#で使える便利な初期化方法を調べてみました。

配列の初期化

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

ジャグ配列、多次元配列の初期化

int[][] example2 = new int[][] {
  new int[] { 3, 1, 4 },
  new int[] { 1, 5, 9 }
};

int[,] example3 = new int[,] {
  { 3, 1, 4 },
  { 1, 5, 9 }
};

構造体の初期化

public struct Example
{
  public string name;
  public int value;
}
Example example4 = new Example { name = "name", value = 1 };

Example[] example5 = new Example[] {
  new Example { name = "name1", value = 2 },
  new Example { name = "name2", value = 3 }
};

List<T>やDictionary<T>も次のようにして使えるそうです。

List<int> example6 = new List<int> { 3, 1, 4, 1, 5 };

Dictionary<string, int> example7 = new Dictionary<string, int> {
  { "name3", 4 },
  { "name4", 5 }
}

リンク

構造体の使用 (C# プログラミング ガイド) | Microsoft Docs
https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/classes-and-structs/using-structs

C#のコードを書くときに参考になる公式リンク

IEnumerable<T>のインターフェイス

IEnumerable(T) Interface (System.Collections.Generic)
https://msdn.microsoft.com/en-us/library/9eekhta0(v=vs.110).aspx

LINQ standard query operators

Standard Query Operators Overview (C#) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/standard-query-operators-overview

<summary>などのDocumentation Commentsタグ

Recommended Tags for Documentation Comments (C# Programming Guide) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/recommended-tags-for-documentation-comments