コガネブログ

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

【C#】基底クラスを継承しているもしくはインターフェイスを実装している場合 true を返す拡張メソッド

概要

/// <summary>
/// 指定された基底クラスを継承しているもしくはインターフェイスを実装している場合 true を返します
/// </summary>
public static bool IsInherits( this Type self, Type baseOrInterfaceType )
{
    if ( self == null ) return false;
    if ( baseOrInterfaceType == null ) return self.IsInterface || self == typeof( object );
    if ( baseOrInterfaceType.IsInterface ) return self.GetInterfaces().Contains( baseOrInterfaceType );

    var currentType = self;

    while ( currentType != null )
    {
        if ( currentType.BaseType == baseOrInterfaceType ) return true;
        currentType = currentType.BaseType;
    }

    return false;
}

参考サイト様