2016-06-12 18 views
-1

指定されていない限り、その親総称である子供のために動作しません:IsSubclassOf()一般的なタイプは、以下のクラスを考える

class A<T> { ... } 
class B1: A<int> { ... } 
class B2: A<string> { ... } 
class C: B1 { ... } 
class D: B2 { ... } 

私たちは、次のような結果があります。今

typeof(C).IsSubclassOf(typeof(A<>))  // returns false 
typeof(C).IsSubclassOf(typeof(A<int>) // returns true 

を、問題は、Bの一般的なタイプが何であるかわからない場合です。私たちの型が基本ジェネリッククラスA <から降りてくるかどうかを、どうやって判断できますか?

bool IsDescebdedFromA(object x) 
{ 
    return typeof(x).IsSubclassOf(typeof(A<>)); // does not give correct result. we have to specify generic type. 
} 

おかげで、すでに

+0

注意を。 – poke

答えて

0

あなたはtype.BaseTypeを使用して継承チェーンをクロールし、問題のジェネリック型への一般的な先祖タイプのジェネリック型定義を比較する必要があります。

私はそれを見つけなければなりませんでしたが、私は同様の質問に回答した投稿があります:How to Identify If Object Is Of A Base Generic Type?

関連するコードスニペットは以下の通りです:ジェネリック型A<>をすることができ、実際のタイプではありませんので

bool IsDescendedFromA1(object x) 
{ 
    return IsInstanceOfGenericTypeClosingTemplateOrSubclassThereof(x, typeof(A<>)); 
} 
2

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 
関連する問題