代码之家  ›  专栏  ›  技术社区  ›  Mong Zhu Bart de Boer

为什么Type.IsGenericType对于没有从方法反射获得的返回类型但typeof(Task)的任务返回TRUE.IsGenericTyp返回FALSE

  •  2
  • Mong Zhu Bart de Boer  · 技术社区  · 6 年前

    IsGenericType

    指示当前类型是否表示泛型类型或方法定义中的类型参数。

    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类型
    是的

    1 回复  |  直到 6 年前
        1
  •  3
  •   Kevin Gosse    6 年前

    在某些情况下,框架返回 Task<VoidTaskResult> 伪装成一个 Task . 想象一下你有一些逻辑依据 TaskCompletionSource<T> T 泛型参数。你可以用 TaskCompletionSource<object> ,但这将浪费相当于指针的内存(32位4字节,64位8字节)。为了避免这种情况,框架使用空结构: VoidTaskResult .