我有一个MethodInfo of a GenericMethodDefinition。例如:CallMethod<T>(T arg, string arg2)。GetParameters()方法将提供两个ParameterInfo对象,第一个是泛型对象,第二个不是泛型对象。如何让ParameterInfo告诉我它是通用的?如果它有约束呢?
发布于 2011-01-20 01:59:15
检查ParameterType.IsGenericParameter。
您可能还想检查ContainsGenericParameters,这对于像MyMethod<T>(List<T> param)这样的东西是正确的。(即使List<>不是泛型参数)
如果IsGenericParameter为真,您还可以调用GetGenericParameterConstraints()来获取接口或基类型约束,并且可以检查GenericParameterAttributes ( [Flags]枚举)中的new()、struct或class约束。
发布于 2011-01-20 02:00:51
我认为你正在寻找这些:
parameterInfo.ParameterType.ContainsGenericParameters
parameterInfo.ParameterType.GetGenericParameterConstraints()发布于 2011-01-20 02:21:18
除了其他人对第二个问题的回答之外:是的,我们可以使用GetGenericParameterConstraints()从ParameterInfo获得约束,但它并不适用于所有情况。考虑下面这样的泛型方法:
public static void MyMethod<T,V>() where T : Dictionary<int, int>
{
}这个方法有一个约束,但是这个方法没有参数(想想Enumerable.Cast)。我要说的是,约束不是参数的一部分,而是方法本身。我们可以通过以下方式获得约束:
method.GetGenericArguments()[0].BaseType //the constraint of T
method.GetGenericArguments()[1].BaseType //that of V: Objecthttps://stackoverflow.com/questions/4738826
复制相似问题