In the following code we have two classes, the Parent class uses generics:
abstract class Parent<T>
{
public T Put(T id, char value)
{
return id;
}
}
class Child : Parent<int>
{
public string Get(Guid guid)
{
return "aei";
}
}
But using reflection IsGenericType on the id parameter we get False...
I think that should be True, right?
Here is my test code:
public static void Main(string[] args)
{
foreach (var methodInfo in typeof(Child).GetMethods())
{
if (!methodInfo.IsVirtual && methodInfo.GetParameters().Length > 0)
{
Console.WriteLine(methodInfo.Name);
foreach (var param in methodInfo.GetParameters())
{
Console.Write(" " + param.Name + " IsGenericType=");
Console.WriteLine(param.ParameterType.IsGenericType);
}
}
}
}
And output:
Get
guid IsGenericType=False
Put
id IsGenericType=False
value IsGenericType=False
Well the result is correct. Child is not generic as in
class Child<T> : Parent<T>
but derived from Parent<int>. So the signature of Child.Put is
int Put(int id, char value);
and so id is not of a generic type, but of type int.
Edit:
A way to get that information could be something like this:
Type childType = typeof(Child);
MethodInfo childPut = childType.GetMethod("Put");
// get the type that initially declared the method
Type declaringType = childPut.DeclaringType;
if (declaringType.IsGenericType)
{
// get the generic type definition (not the constructed Parent<int>)
Type genericType = declaringType.GetGenericTypeDefinition();
MethodInfo genericMethod = genericType.GetMethod("Put");
ParameterInfo genericParam = genericMethod.GetParameters().First();
// use IsGenericParameter - we want to know that the type is determined
// by a generic argument, not if that type argument itself is generic
Console.WriteLine(genericParam.ParameterType.IsGenericParameter);
}
This outputs true for your (special) case. I don't know your requirements, for which types the method should work. As I said in the comments, to make this an algorithm that can determine this for each parameter for all cirumstances seems complicated to me.
Tis not a generic type, it's a generic type parameter which is not the same thing.
A generic type is SomeType<T> but T can be string or int or whatever, which are not generic types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With