Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given the following example class:

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

If I am reflecting against method Foo<>.Bar<>(...), and examining the parameter types, say:

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

both argType1 and argType2 look similar:

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

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

like image 913
nicholas Avatar asked Oct 17 '22 17:10

nicholas


1 Answers

I suppose, like so:

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

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

    }
}
like image 114
eocron Avatar answered Oct 20 '22 11:10

eocron