簡體   English   中英

為什么Type.IsGenericType為Task返回TRUE,而沒有通過方法的反射獲得返回類型,但是typeof(Task).IsGenericTyp返回FALSE

[英]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
真正

在某些情況下,框架返回偽裝為TaskTask<VoidTaskResult> 想象一下,您有一些邏輯依賴TaskCompletionSource<T> 如果您實際上並不打算返回結果,則仍然必須填寫T泛型參數。 您可以使用TaskCompletionSource<object> ,但是您將浪費指針的內存空間(32位為4字節,64位為8字節)。 為了避免這種情況,框架使用了一個空結構: VoidTaskResult

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM