考虑以下类:
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()
,您可能不想要。即:
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]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句