例:次のクラスがあります。
public class A {}
public class B:A {}
public class C:B {}
public class D:C {}
(D.IsSubclassOf(B)をテストする代わりに)基本クラスまでの階層距離を取得して、DがAに近いか、BがAに近いかを判断するような便利な方法がある場合は、
多分これは何か助けになります:
public static int? GetDegreeOfRelationship(Type typeA, Type typeB)
{
if (typeA.IsInterface || typeB.IsInterface) return null; // interfaces are not part of the inheritance tree
if (typeA == typeB) return 0;
int distance = 0;
Type child;
if (typeA.IsAssignableFrom(typeB))
{
child = typeB;
while ((child = child.BaseType) != typeA)
distance--;
return --distance;
}
else if(typeB.IsAssignableFrom(typeA))
{
child = typeA;
while ((child = child.BaseType) != typeB)
distance++;
return ++distance;
}
else
return null;
}
使用法:
int? distance = GetDegreeOfRelationship(typeof(A), typeof(D)); // -3
int? distance = GetDegreeOfRelationship(typeof(D), typeof(A)); // 3
int? distance = GetDegreeOfRelationship(typeof(B), typeof(B)); // 0
int? distance = GetDegreeOfRelationship(typeof(D), typeof(string)); // null
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加