コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】指定した型の基底クラスの情報をすべて取得する拡張メソッド

ソースコード

using System;
using System.Collections.Generic;

/// <summary>
/// Type 型の拡張メソッドを管理するクラス
/// </summary>
public static class TypeExtensions
{
    /// <summary>
    /// 指定された Type の継承元であるすべての型を取得します
    /// </summary>
    public static IEnumerable<Type> GetBaseTypes(this Type self)
    {
        for (var baseType = self.BaseType; null != baseType; baseType = baseType.BaseType)
        {
            yield return baseType;
        }
    }
}

使い方

class Character
{
}

class Player : Character
{
}

class Hero : Player
{
}

void Awake()
{
    var type = typeof(Hero);
    foreach (var n in type.GetBaseTypes())
    {
        Debug.Log(n.Name);
    }
}
Player
Character
Object

関連記事