简体   繁体   English

C# 反射 - 从基类中获取超类的通用参数类型

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

Consider the classes:考虑类:

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
    }
}

Does anyone know how to get the generic type from within the base class without calling typeof(TArg) because I'll be iterating through other super classes properties and it must be via deeper reflection.有谁知道如何在不调用typeof(TArg)情况下从基类中获取泛型类型,因为我将遍历其他超类属性,并且必须通过更深层次的反射。

Thanks.谢谢。

You've got a call to GetGenericTypeDefinition() , which you probably don't want.您收到了对GetGenericTypeDefinition()的调用,这可能是您不想要的。 Ie: IE:

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

typeof(TSuper).GetProperty("Next").PropertyType.BaseType returns the type Base<Test, Super> . typeof(TSuper).GetProperty("Next").PropertyType.BaseType返回类型Base<Test, Super> So calling GetGenericArguments() on it returns [Test, Super] .所以调用GetGenericArguments()会返回[Test, Super]

Calling GetGenericTypeDefinition() on that gives you Base<TArg, TSuper> , and calling GetGenericArguments() on it returns [TArg, TSuper] .调用GetGenericTypeDefinition()给你Base<TArg, TSuper> ,调用GetGenericArguments()返回[TArg, TSuper]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM