C# 了解此返回类型对象的函数
我有一个很酷的方法来检查一个类型是否派生自另一个类型。当我重构代码时,我得到了这个块C# 了解此返回类型对象的函数,c#,generics,inheritance,reflection,types,C#,Generics,Inheritance,Reflection,Types,我有一个很酷的方法来检查一个类型是否派生自另一个类型。当我重构代码时,我得到了这个块GetBlah public static bool IsOf(this Type child, Type parent) { var currentChild = child.GetBlah(parent); while (currentChild != typeof(object)) { if (parent == currentChild)
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
或List
。它们都使用相同的泛型类型定义:List
IsGenericType
将返回true
类型是否为泛型类型。
如果类型是泛型类型定义IsGenericTypeDefinition
应返回true。
函数GetGenericTypeDefinition
将返回泛型类型的泛型类型定义
因此,如果你愿意:
typeof(List<int>).GetGenericTypeDefinition();
给定的代码在某一点失败:每次父对象
的类型为对象
时,返回false。通过将while条件修改为:
while (currentChild != null)
现在转到您的Blah
-函数。检查父项是否为泛型类型定义。不能从泛型类型定义派生任何“普通”类(泛型或非泛型)。只有泛型类型定义可以从另一个泛型类型定义派生。因此,为了使情况G和H变为真,必须做一个特殊的变换。如果父项是泛型类型定义,并且子项可以转换为泛型类型定义,则子项将转换为其泛型类型定义
这就是它的全部功能
因此,函数的完美名称可以是:convertChildTogenericTypeDefinitionIfParentisGenericTypeDefinition和ThechildisGenericTypeDefinition(…)
:)?!我已经回答了你关于GetBlah方法的问题,但是你想做什么呢?已存在
类型。IsAssignableFrom
方法。您还想知道List
是否源自List
?如果您需要帮助,请发布第二个问题(并用新链接给我一个评论!)@Patashu这听起来像是正确的答案,您能给出答案吗?@user287107与什么不同<代码>IsOf方法?或者GetBlah
method?马丁,我想你还没有回答我的问题。我知道这些是什么意思。我不明白的是它们在代码中的相关性。换句话说,他们使用GetBlah
方法的目的是什么@我认为帕塔舒在评论中表达得很好。要获取GetPossibleGenericTypeDefinition
,我需要做的就是child.IsGenericTypeDefinition?GetGenericTypeDefinition():child
,但该方法中也有parent
参数,它在那里做一些事情。我不明白那个论点的相关性——这就是我的问题所在。
while (currentChild != null)