:
bool IsInstanceOfGenericTypeClosingTemplateOrSubclassThereof(object obj, Type genericTypeDefinition){
if(obj == null) throw new ArgumentNullException("obj");
if(genericTypeDefinition== null) throw new ArgumentNullException("genericTypeDefinition");
if(!genericTypeDefinition.IsGenericTypeDefinition) throw new ArgumentException("Must be a generic type definition.", "genericTypeDefinition");
Type type = obj.GetType();
while (type != typeof(object))
{
if(type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition)
{
return true;
}
type = type.BaseType;
}
return false;
}
あなたはその後、同じようにそれを呼び出しますインスタンス化されると、そのサブクラスは存在しません。そのため、タイプが汎用タイプA<>
のサブクラスかどうかを確認するには、手動でタイプ階層をトラバースする必要があります。
これは、例えば、次のようになります。
bool IsSubclassOfGeneric(Type current, Type genericBase)
{
do
{
if (current.IsGenericType && current.GetGenericTypeDefinition() == genericBase)
return true;
}
while((current = current.BaseType) != null);
return false;
}
は次のように使用される: `typeof演算(x)は`動作しないこと
Console.WriteLine(IsSubclassOfGeneric(typeof(A<>), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(A<int>), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(B1), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(B2), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(C), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(D), typeof(A<>)));
Console.WriteLine(IsSubclassOfGeneric(typeof(string), typeof(A<>))); // false
注意を。 – poke