簡體   English   中英

C# 反射 - 從基類中獲取超類的通用參數類型

[英]C# Reflection - Get Generic Argument type of Super class from within the Base class

考慮類:

public class Super : Base<Test, Super>
{
    public Super Next { get; set; }
}

public class Base<TArg, TSuper>
{
    public Type GetTestArgument()
    {
        Type[] arguments = typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericTypeDefinition().GetGenericArguments();
        // arguments is set to [ TArg, TSuper ] instead of [ Test, Super ]
        return arguments[0]; // should be Test
    }
}

有誰知道如何在不調用typeof(TArg)情況下從基類中獲取泛型類型,因為我將遍歷其他超類屬性,並且必須通過更深層次的反射。

謝謝。

您收到了對GetGenericTypeDefinition()的調用,這可能是您不想要的。 IE:

typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericArguments()

typeof(TSuper).GetProperty("Next").PropertyType.BaseType返回類型Base<Test, Super> 所以調用GetGenericArguments()會返回[Test, Super]

調用GetGenericTypeDefinition()給你Base<TArg, TSuper> ,調用GetGenericArguments()返回[TArg, TSuper]

暫無
暫無

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

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