C# 为什么Type.IsGenericType对于没有从方法反射获得的返回类型的任务返回TRUE,但是typeof(Task)返回FALSE
有人能解释一下吗?根据文件 指示当前类型是否表示泛型类型或方法定义中的类型参数 所以这个(LINQPad)代码: 按预期工作并产生输出: 类型(任务)。IsGenericTypeC# 为什么Type.IsGenericType对于没有从方法反射获得的返回类型的任务返回TRUE,但是typeof(Task)返回FALSE,c#,generics,task,C#,Generics,Task,有人能解释一下吗?根据文件 指示当前类型是否表示泛型类型或方法定义中的类型参数 所以这个(LINQPad)代码: 按预期工作并产生输出: 类型(任务)。IsGenericType 假的 但当我通过反射从方法中检索它时: public class MyClass { public async Task Method() { await Task.Run(() => { Thread.Sleep(3000);
假的 但当我通过反射从方法中检索它时:
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");
}
公共类MyClass
{
公共异步任务方法()
{
等待任务。运行(()=>
{
睡眠(3000);
});
}
}
公共异步任务测试()
{
MyClass theObject=新的MyClass();
任务任务=(任务)类型(MyClass).GetTypeInfo()
.GetDeclaredMethod(“方法”)
.Invoke(对象,空);
bool b=task.GetType().IsGenericType;
bool b2=task.GetType().GetGenericTypeDefinition()==typeof(任务);
b、 转储(“IsGenericType”);
b2.转储(“GetGenericTypeDefinition”);
bool bStraight=typeof(Task).IsGenericType;
Dump(“typeof(Task).IsGenericType”);
}
我得到以下意外输出:
IsGenericType正确
GetGenericTypeDefinition
真的
在某些情况下,框架返回一个伪装成
任务的任务
。假设您有一些依赖于TaskCompletionSource
的逻辑。如果您实际上不打算返回结果,则仍然必须填写t
generic参数。您可以使用TaskCompletionSource
,但这会浪费相当于指针的内存(32位4字节,64位8字节)。为了避免这种情况,框架使用了一个空结构:VoidTaskResult
仔细查看task.GetType()
,您会发现它是一个任务
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");
}