[英]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.