What is the most efficient way to ask a MethodInfo how many parameters it takes?

只愿长相守 提交于 2019-12-23 08:49:25

问题


What is the most efficient way to ask a MethodInfo if it accepts parameters and, if so, how many?

My current solutions would be: methodInfo.GetParameters().Any() and methodInfo.GetParameters().Count().

Is this the most efficient way?

Since I don't actually need any of the ParameterInfo objects, is there a way to do this without a call to GetParameters()?


回答1:


The two you listed are for LINQ. Any() returns bool - stating that there is at least one. Count() is used any on IEnumerable<T>.

Length (the property) will be the fastest because GetParameters() returns ParameterInfo[].

It does not appear that MethodInfo have any other way to access the number of parameters other than GetParameters().




回答2:


If efficiency matters why don't you just cache the result in a Dictionary<MethodInfo,int>? That way you only need to use reflection only once.




回答3:


If you want to get the count of parameters of a MethodInfo, then use the below code

int intLength = mi.GetParameters().Length; // where mi is a variable of type MethodInfo


来源:https://stackoverflow.com/questions/4949503/what-is-the-most-efficient-way-to-ask-a-methodinfo-how-many-parameters-it-takes

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