Distinguish between a generic class type parameter and a generic method type parameter

Given the following class example:

class Foo<T> { void Bar<S>(T inputT, S inputS) { // Some really magical stuff here! } } 

If I reflect on the Foo<>.Bar<>(...) method and study parameter types, let's say:

 var argType1 = typeof(Foo<>).GetMethod("Bar").GetParameters()[0].ParameterType; var argType2 = typeof(Foo<>).GetMethod("Bar").GetParameters()[1].ParameterType; 

both argType1 and argType2 look the same:

  • FullName property is null
  • Name property is "T" or "S" respectively
  • IsGenericParameter true

Is there anything in the parameter type information that allows me to distinguish the first argument from the type level, while the second argument is a method type parameter?

+5
source share
1 answer

I suppose for example:

  public static bool IsClassGeneric(Type type) { return type.IsGenericParameter && type.DeclaringMethod == null; } 

And in the code:

 class Program { static void Main(string[] args) { new Foo<int>().Bar<int>(1,1); } class Foo<T> { public void Bar<S>(T a, S b) { var argType1 = typeof(Foo<>).GetMethod("Bar").GetParameters()[0].ParameterType; var argType2 = typeof(Foo<>).GetMethod("Bar").GetParameters()[1].ParameterType; var argType1_res = Ext.IsClassGeneric(argType1);//true var argType2_res = Ext.IsClassGeneric(argType2);//false } } } 
+3
source

Source: https://habr.com/ru/post/1263795/


All Articles