![](/img/trans.png)
[英]Why does the method return a string when return type is Task<string>?
[英]Why does Type.IsGenericType return TRUE for Task without return type obtained by reflection from method but typeof(Task).IsGenericTyp returns FALSE
有人可以解释吗? 根据文档IsGenericType
指示当前Type是泛型类型或方法定义中的类型参数。
因此,此(LINQPad)代码为:
bool bStraight = typeof(Task).IsGenericType;
bStraight.Dump("typeof(Task).IsGenericType");
按预期工作并产生输出:
的typeof(任务).IsGenericType
假
但是当我通过反射从方法中检索它时:
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
的Task<VoidTaskResult>
。 想象一下,您有一些逻辑依赖TaskCompletionSource<T>
。 如果您实际上并不打算返回结果,则仍然必须填写T
泛型参数。 您可以使用TaskCompletionSource<object>
,但是您将浪费指针的内存空间(32位为4字节,64位为8字节)。 为了避免这种情况,框架使用了一个空结构: VoidTaskResult
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.