[英]Why does Type.IsGenericType return TRUE for Task without return type obtained by reflection from method but typeof(Task).IsGenericTyp returns FALSE
Can someone explain this? 有人可以解释吗? Per documentation IsGenericType
根据文档IsGenericType
indicatesing whether the current Type represents a type parameter in the definition of a generic type or method.
指示当前Type是泛型类型或方法定义中的类型参数。
So this (LINQPad) code: 因此,此(LINQPad)代码为:
bool bStraight = typeof(Task).IsGenericType;
bStraight.Dump("typeof(Task).IsGenericType");
works as expected and yields the output: 按预期工作并产生输出:
typeof(Task).IsGenericType
的typeof(任务).IsGenericType
False假
But when I retrieve it from a method by 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");
}
I get the unexpected output of : 我得到了意外的输出:
IsGenericType
IsGenericType
True真正
GetGenericTypeDefinition
GetGenericTypeDefinition
True真正
In some situations, the framework returns a Task<VoidTaskResult>
disguised as a Task
. 在某些情况下,框架返回伪装为
Task
的Task<VoidTaskResult>
。 Imagine you have some logic relying on TaskCompletionSource<T>
. 想象一下,您有一些逻辑依赖
TaskCompletionSource<T>
。 If you don't actually intend to return a result, you still have to fill the T
generic parameter. 如果您实际上并不打算返回结果,则仍然必须填写
T
泛型参数。 You could use TaskCompletionSource<object>
, but you would be wasting a pointer worth of memory (4 bytes in 32 bit, 8 bytes in 64 bit). 您可以使用
TaskCompletionSource<object>
,但是您将浪费指针的内存空间(32位为4字节,64位为8字节)。 To avoid that, the framework uses an empty struct: VoidTaskResult
. 为了避免这种情况,框架使用了一个空结构:
VoidTaskResult
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.