我有一个 MethodInfo 通用定义。如: CallMethod<T>(T arg, string arg2). 。 getParameters()方法将为我提供两个parameterinfo对象,第一个对象是通用的,其中第二个不是。如何获得参数info告诉我它是通用的?如果它有限制呢?

有帮助吗?

解决方案

查看 ParameterType.IsGenericParameter.
您可能还想检查 ContainsGenericParameters, ,这对类似 MyMethod<T>(List<T> param). 。 (虽然 List<> 不是通用参数)

如果 IsGenericParameter 是的,你也可以打电话 GetGenericParameterConstraints() 要获得接口或基本类型约束,您可以检查 GenericParameterAttributes (一个 [Flags] 枚举) new(), struct, , 或者 class 约束。

其他提示

我认为您正在寻找这些:

parameterInfo.ParameterType.ContainsGenericParameters
parameterInfo.ParameterType.GetGenericParameterConstraints()

除了他人对第二个问题的回答外:是的,我们可以从中获得约束 ParameterInfo 使用 GetGenericParameterConstraints(), ,但在所有情况下都没有用。考虑一些这样的通用方法:

public static void MyMethod<T,V>() where T : Dictionary<int, int>
{
}

该方法有一个约束,但是该方法没有参数(考虑一下 枚举)。我要说的是,约束不是参数的一部分,而是方法本身。我们可以通过:

method.GetGenericArguments()[0].BaseType  //the constraint of T
method.GetGenericArguments()[1].BaseType  //that of V: Object

也许 这里 您将找到有关反映通用参数的信息...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top