c# - 为什么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
真
解决方案
在某些情况下,框架返回一个Task<VoidTaskResult>
伪装成Task
. 想象一下,您有一些逻辑依赖于TaskCompletionSource<T>
. 如果您实际上不打算返回结果,您仍然需要填写T
泛型参数。您可以使用TaskCompletionSource<object>
,但您会浪费一个内存指针(32 位中的 4 个字节,64 位中的 8 个字节)。为避免这种情况,框架使用了一个空结构:VoidTaskResult
。
推荐阅读
- javascript - 正则表达式'/code.? * (\w {4}) /' 不起作用
- javascript - 如何在 jQuery 中暂停 FadeTo() 方法?
- angularjs - Angular JS - 如何从另一个元素的事件中更改输入的值
- python - Shutil zipping error和shutil rmtree错误,帮我理解
- pandas - 用pandas过滤DataFrame中满足另一个DataFrame条件的多个单独行?
- outlook - 如何将数据从 SQL Azure 导入 O365 Outlook 日历
- javascript - 为什么我的 Array.prototype.find() 返回未定义?
- time-series - Stata时间序列滚动预测
- node.js - 使用 MongoDB 和 NodeJS 更新数组中的字段
- reactjs - React/redux:我必须重新加载页面才能删除