【问题标题】:What is the most efficient way to ask a MethodInfo how many parameters it takes?询问 MethodInfo 需要多少参数的最有效方法是什么?
【发布时间】:2011-06-24 09:14:33
【问题描述】:

询问 MethodInfo 是否接受参数最有效的方法是什么,如果接受,有多少?

我目前的解决方案是:methodInfo.GetParameters().Any()methodInfo.GetParameters().Count()

这是最有效的方法吗?

由于我实际上不需要任何 ParameterInfo 对象,有没有办法在不调用 GetParameters() 的情况下做到这一点?

【问题讨论】:

    标签: c# performance reflection methodinfo


    【解决方案1】:

    您列出的两个用于 LINQ。 Any() 返回bool - 说明至少有一个。 Count() 用于 IEnumerable<T> 上的任何一个。

    Length(属性)将是最快的,因为GetParameters() 返回ParameterInfo[]

    除了GetParameters()之外,MethodInfo似乎没有其他方法可以访问参数数量。

    【讨论】:

    • 您是否熟悉 MethodImplAttributes 或者您知道它们是否可用于确定这一点?
    • 我不是个人。它看起来并不适用。
    • @smartcaveman: MethodImplAttributes 指定方法实现细节。正如丹尼尔正确假设的那样,它与方法参数的数量无关。
    【解决方案2】:

    如果效率很重要,为什么不将结果缓存在Dictionary<MethodInfo,int> 中?这样你只需要使用一次反射。

    【讨论】:

      【解决方案3】:

      如果要获取MethodInfo 的参数个数,请使用以下代码

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 2022-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多