繁体   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