C# 如何确定ParameterInfo是否为泛型类型?
我有一个GenericMethodDefinition的C# 如何确定ParameterInfo是否为泛型类型?,c#,generics,reflection,methodinfo,parameterinfo,C#,Generics,Reflection,Methodinfo,Parameterinfo,我有一个GenericMethodDefinition的MethodInfo。例如:CallMethod(T arg,字符串arg2)。GetParameters()方法将为我提供两个ParameterInfo对象,第一个是泛型对象,第二个不是泛型对象。如何让ParameterInfo告诉我它是通用的?如果它有约束呢?检查参数类型.IsGenericParameter 您可能还需要检查ContainsGenericParameters,这对于MyMethod(List param)之类的内容是正
MethodInfo
。例如:CallMethod(T arg,字符串arg2)
。GetParameters()方法将为我提供两个ParameterInfo对象,第一个是泛型对象,第二个不是泛型对象。如何让ParameterInfo告诉我它是通用的?如果它有约束呢?检查参数类型.IsGenericParameter
您可能还需要检查
ContainsGenericParameters
,这对于MyMethod(List param)
之类的内容是正确的。(即使List
不是通用参数)
如果
IsGenericParameter
为true,您还可以调用GetGenericParameterConstraints()
来获取接口或基类型约束,并且您可以检查GenericParameterAttributes
(a[Flags]
enum)中的new()
,struct
,或者类
约束。也许您会找到有关反映通用参数的信息…我想您正在寻找这些:
parameterInfo.ParameterType.ContainsGenericParameters
parameterInfo.ParameterType.GetGenericParameterConstraints()
除了其他人对第二个问题的回答之外:是的,我们可以使用
GetGenericParameterConstraints()
从ParameterInfo
获取约束,但它并不适用于所有情况。考虑一些类似的方法:
public static void MyMethod<T,V>() where T : Dictionary<int, int>
{
}
一般参数约束呢?如果
args
是T[]
的数组,则可以使用ParameterType.IsArray
和ParameterType.ContainsGenericParameter
。感谢mods创建parameterinfo标记
method.GetGenericArguments()[0].BaseType //the constraint of T
method.GetGenericArguments()[1].BaseType //that of V: Object