Cooooding!!

Unity(C#)を使ったゲーム開発関連Tipsなど

TypeがStructかどうかを判定する【C#】

概要

System.Typeがstructかどうかを判定しようと思ったら、System.Type.IsClassはあるのに何故かIsStructがなかったので判定方法を調べてみました。

判定方法

判定はIsValueTypeやIsPrimitiveなどを組み合わせて実装します。

public static bool IsStruct(System.Type type)
{
    return type.IsValueType &&  // 値型に限定(classを除外)
        !type.IsPrimitive &&    // intやfloatなどを除外
        !type.IsEnum;           // enumを除外(enumはValueTypeだけどPrimitiveではない)
}

サンプルコード

UnityEngine.Debug.Log(IsStruct(typeof(int)));
UnityEngine.Debug.Log(IsStruct(typeof(string)));
UnityEngine.Debug.Log(IsStruct(typeof(UnityEngine.Vector2)));
UnityEngine.Debug.Log(IsStruct(typeof(UnityEngine.Rect)));
UnityEngine.Debug.Log(IsStruct(typeof(UnityEngine.MonoBehaviour)));
UnityEngine.Debug.Log(IsStruct(typeof(UnityEngine.TextureFormat)));

実行結果

False
False
True
True
False
False

環境

  • Unity 2019.1.9f1
  • VisualStudio 2019