クラスがジェネリッククラスから派生しているかどうかを確認する 質問する

クラスがジェネリッククラスから派生しているかどうかを確認する 質問する

私のプロジェクトには派生クラスを持つジェネリッククラスがあります。

public class GenericClass<T> : GenericInterface<T>
{
}

public class Test : GenericClass<SomeType>
{
}

Typeオブジェクトが から派生したものであるかどうかを確認する方法はありますかGenericClass?

t.IsSubclassOf(typeof(GenericClass<>))

動作しません。

ベストアンサー1

このコードを試してください

static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
    while (toCheck != null && toCheck != typeof(object)) {
        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
        if (generic == cur) {
            return true;
        }
        toCheck = toCheck.BaseType;
    }
    return false;
}

おすすめ記事