Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 了解此返回类型对象的函数_C#_Generics_Inheritance_Reflection_Types - Fatal编程技术网

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)