2
2

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 1 year has passed since last update.

C# enum(列挙型)からのint(整数)、string(文字列)への変換

Posted at

0.0 はじめに

C#の列挙型enum(イーナム)はswitch文などでとても活躍しますが、実はデフォルトで各定数に対して0(ゼロ)から順番に整数値が付けられています。
ちなみにこの数値は =100 のように自分で設定することができます。
また、列挙型enumの各定数を文字列として使うこともできます。
これらの使い方を説明します。

1.0 enumの整数や文字列の使い方

下記スクリプト内のStart関数を見てください。
数値にするには(int)でキャスト、文字列にするにはToString()を使います。

C# Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    // enumの定義
    enum Num {
        ZERO, // = 0
        ONE, // = 1
        TWO, // = 2
        SOME = 100,
    }

    Num num = Num.ONE;

    private void Start() {
        Debug.Log("NUM.ZEROのenum型は " + Num.ZERO + " です");
        Debug.Log("NUM.ONEの数字は" + (int)Num.ONE + " です");
        Debug.Log("NUM.TWOの文字は" + Num.TWO.ToString() + " です");
        Debug.Log("Num.SOMEの数字は" + (int)Num.SOME + " です");
    }
}

実行するとこのような感じになります。
image.png

2.0 整数や文字列からのenumへの変換方法

下記スクリプト内のStart関数を見てください。
Enumを使いますので頭にusing System;の追加が必要です。

C# Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System; // 追加

public class Test : MonoBehaviour
{
    // enumの定義
    enum Num {
        ZERO, // = 0
        ONE, // = 1
        TWO, // = 2
        SOME = 100,
    }

    Num num = Num.ONE;

    private void Start() {
        Debug.Log("整数100をeunm型Numに変換すると " + (Num)Enum.ToObject(typeof(Num), 100) + " です");
        Debug.Log("文字ZEROをeunm型Numに変換すると " + (Num)Enum.Parse(typeof(Num), "ZERO") + " です");
    }
}

実行するとこのような感じになります。
image.png

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?