简体   繁体   English

如何确定ParameterInfo是否是泛型类型?

[英]How to determine if ParameterInfo is of generic type?

I have a MethodInfo of a GenericMethodDefinition. 我有一个GenericMethodDefinition的MethodInfo Such as: CallMethod<T>(T arg, string arg2) . 如: CallMethod<T>(T arg, string arg2) The GetParameters() method will give me two ParameterInfo objects, the first of which is generic, the second of which is not. GetParameters()方法将为我提供两个ParameterInfo对象,第一个是通用的,第二个不是。 How can I get ParameterInfo to tell me it is generic? 如何让ParameterInfo告诉我它是通用的? What about if it has constraints? 如果它有约束怎么办?

Check ParameterType.IsGenericParameter . 检查ParameterType.IsGenericParameter
You may also want to check ContainsGenericParameters , which will be true for something like MyMethod<T>(List<T> param) . 您可能还想检查ContainsGenericParameters ,对于像MyMethod<T>(List<T> param)这样的东西也是如此。 (Even though List<> isn't a generic parameter) (即使List<>不是通用参数)

If IsGenericParameter is true, you can also call GetGenericParameterConstraints() to get interface or base type constraints, and you can check GenericParameterAttributes (a [Flags] enum) for new() , struct , or class constraints. 如果IsGenericParameter为true,您还可以调用GetGenericParameterConstraints()来获取接口或基类型约束,并且可以检查GenericParameterAttributes[Flags]枚举)是否有new()structclass约束。

I think you are looking for these: 我想你正在寻找这些:

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

In additional to others' answer to the second question: Yes we can get the constraints from ParameterInfo using GetGenericParameterConstraints() , but it doesn't work for all circumstances. 除了其他人对第二个问题的回答:是的,我们可以使用GetGenericParameterConstraints()ParameterInfo获取约束,但它并不适用于所有情况。 Consider some generic method like this: 考虑一些像这样的通用方法:

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

There is a constraint for this method, but the method doesn't have parameters(think about Enumerable.Cast ). 此方法存在约束,但该方法没有参数(请考虑Enumerable.Cast )。 What I'm going to say is the constraint is not part of the parameters, but the method itself. 我要说的是约束不是参数的一部分,而是方法本身。 We can get the constraints by: 我们可以通过以下方式获得约束

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

也许在这里你会找到有关反映通用参数的信息......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM