【发布时间】:2013-05-04 13:09:45
【问题描述】:
我有一个很酷的方法here 来检查一个类型是否派生自另一个。当我重构代码时,我得到了这个块GetBlah。
public static bool IsOf(this Type child, Type parent)
{
var currentChild = child.GetBlah(parent);
while (currentChild != typeof(object))
{
if (parent == currentChild)
return true;
if(currentChild.GetInterfaces().Any(i => i.GetBlah(parent) == parent))
return true;
if (currentChild.BaseType == null)
return false;
currentChild = currentChild.BaseType.GetBlah(parent);
}
return false;
}
static Type GetBlah(this Type child, Type parent)
{
return child.IsGenericType && parent.IsGenericTypeDefinition
? child.GetGenericTypeDefinition()
: child;
}
我无法理解 GetBlah 的作用,因此无法为其命名。我的意思是我可以理解三元表达式和GetGenericTypeDefinition 函数,但我似乎没有在IsOf 方法中使用它,尤其是正在传递的parent 参数。有人能解释一下GetBlah 方法实际上返回了什么吗?
奖励:建议我为该方法取一个恰当的名称:)
【问题讨论】:
-
看起来,如果孩子和父母都是泛型但类型不同(例如
List<String>vsList<int>),则该方法旨在制作相同的泛型类型(List<>)所以可以更准确地比较它们。 -
现在与
Type.IsAssignableFrom方法有什么区别?! -
我已经回答了你关于 GetBlah 方法的问题,但你想做什么?已经有一个
Type.IsAssignableFrom方法。您是否还想知道List<int>是否源自List<>?如果您需要帮助,请发布第二个问题(并使用新链接给我评论!):) -
@Patashu 这听起来像是正确的答案,你能把它作为答案吗?
-
@user287107 有什么区别?
IsOf方法?还是GetBlah方法?
标签: c# generics inheritance reflection types