Reputation: 696
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.
Thanks.
Upvotes: 1
Views: 317
Reputation: 42245
You've got a call to GetGenericTypeDefinition()
, which you probably don't want. I.e.:
typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericArguments()
typeof(TSuper).GetProperty("Next").PropertyType.BaseType
returns the type Base<Test, Super>
. So calling GetGenericArguments()
on it returns [Test, Super]
.
Calling GetGenericTypeDefinition()
on that gives you Base<TArg, TSuper>
, and calling GetGenericArguments()
on it returns [TArg, TSuper]
.
Upvotes: 2