How to determine if ParameterInfo is of generic type?

偶尔善良 提交于 2019-11-29 10:25:41

Check ParameterType.IsGenericParameter.
You may also want to check ContainsGenericParameters, which will be true for something like MyMethod<T>(List<T> param). (Even though List<> isn't a generic parameter)

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.

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. 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). 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

Maybe here you will find information about reflecting generic parameters ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!