给定以下示例类:
class Foo<T>
{
void Bar<S>(T inputT, S inputS)
{
// Some really magical stuff here!
}
}
如果我针对方法进行反射(reflection) Foo<>.Bar<>(...)
,并检查参数类型,说:
var argType1 = typeof(Foo<>).GetMethod("Bar").GetParameters()[0].ParameterType;
var argType2 = typeof(Foo<>).GetMethod("Bar").GetParameters()[1].ParameterType;
两者都是argType1
和 argType2
看起来很相似:
-
FullName
属性为空 -
Name
属性分别为“T”或“S” -
IsGenericParameter
是真的
参数类型信息中是否有任何内容可以让我区分第一个参数是在类型级别定义的,而第二个参数是方法级别的类型参数?
最佳答案
我想,像这样:
public static bool IsClassGeneric(Type type)
{
return type.IsGenericParameter && type.DeclaringMethod == null;
}
在代码中:
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
}
}
}
关于c# - 区分类泛型类型参数和方法泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42028702/