为什么Type.IsGenericType为Task返回TRUE而没有通过方法reflection获得的返回类型但是typeof(Task).IsGenericTyp返回FALSE

有人可以解释一下吗? 每个文档IsGenericType

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

所以这个(LINQPad)代码:

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

按预期工作并产生输出:

的typeof(任务).IsGenericType

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

 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
真正

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