首页 > 解决方案 > 为什么Type.IsGenericType为Task返回TRUE而没有通过方法反射获得返回类型但typeof(Task).IsGenericTyp返回FALSE

问题描述

有人可以解释一下吗?根据文档IsGenericType

指示当前 Type 是否表示泛型类型或方法定义中的类型参数。

所以这个(LINQPad)代码:

bool bStraight = typeof(Task).IsGenericType;
bStraight.Dump("typeof(Task).IsGenericType");

按预期工作并产生输出:

typeof(Task).IsGenericType
False

但是当我通过反射从方法中检索它时:

public class MyClass
{
    public async Task Method()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(3000);
        });
    }
}

public async Task TEST()
{
    MyClass theObject = new MyClass();

    Task task = (Task)typeof(MyClass).GetTypeInfo()
                            .GetDeclaredMethod("Method")
                            .Invoke(theObject, null);

    bool b = task.GetType().IsGenericType;  
    bool b2 = task.GetType().GetGenericTypeDefinition() == typeof(Task<>);
    b.Dump("IsGenericType");
    b2.Dump("GetGenericTypeDefinition");

    bool bStraight = typeof(Task).IsGenericType;
    bStraight.Dump("typeof(Task).IsGenericType");
}

我得到了意外的输出:

IsGenericType

GetGenericTypeDefinition

标签: c#genericstask

解决方案


在某些情况下,框架返回一个Task<VoidTaskResult>伪装成Task. 想象一下,您有一些逻辑依赖于TaskCompletionSource<T>. 如果您实际上不打算返回结果,您仍然需要填写T泛型参数。您可以使用TaskCompletionSource<object>,但您会浪费一个内存指针(32 位中的 4 个字节,64 位中的 8 个字节)。为避免这种情况,框架使用了一个空结构:VoidTaskResult


推荐阅读