区分类泛型类型参数和方法泛型类型参数

nic*_*las 5 c# generics reflection

给出以下示例类:

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

如果我反思方法Foo<>.Bar<>(...),并检查参数类型,请说:

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

argType1argType2外观相似:

  • FullName property为null
  • Name 属性分别为"T"或"S"
  • IsGenericParameter 是真的

参数类型信息中是否有任何内容允许我区分第一个参数是在类型级别定义的,而第二个参数是方法级别的类型参数?

eoc*_*ron 3

我想,就像这样:

    public static bool IsClassGeneric(Type type)
    {
        return type.IsGenericParameter && type.DeclaringMethod == null;
    }
Run Code Online (Sandbox Code Playgroud)

并在代码中:

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
        }

    }
}
Run Code Online (Sandbox Code Playgroud)