【问题标题】:How can you get the names of method parameters?如何获取方法参数的名称?
【发布时间】:2010-09-17 20:44:06
【问题描述】:

如果我有这样的方法:

public void MyMethod(int arg1, string arg2)

我将如何获取参数的实际名称? 我似乎在 MethodInfo 中找不到任何实际上会给我参数名称的东西。

我想写一个如下所示的方法:

public static string GetParamName(MethodInfo method, int index)

所以如果我调用这个方法:

string name = GetParamName(MyMethod, 0)

它将返回“arg1”。这可能吗?

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

    nameof(arg1) 将返回变量名arg1

    https://msdn.microsoft.com/en-us/library/dn986596.aspx

    【讨论】:

    • 我几乎完全确定 OP 是指方法的外部。比你早八年离开的所有其他 cmets 似乎也证实了这一点。
    【解决方案2】:

    没有任何类型的错误检查:

    public static string GetParameterName ( Delegate method , int index )
    {
        return method.Method.GetParameters ( ) [ index ].Name ;
    }
    

    您可以使用 'Func' 和派生词来使其适用于大多数情况

    【讨论】:

    • @TomAnderson - 从互联网上盲目复制代码也是自找麻烦!
    【解决方案3】:

    试试这样的:

    foreach(ParameterInfo pParameter in pMethod.GetParameters())
    {
        //Position of parameter in method
        pParameter.Position;
    
        //Name of parameter type
        pParameter.ParameterType.Name;
    
        //Name of parameter
        pParameter.Name;
    }
    

    【讨论】:

      【解决方案4】:
      public static string GetParamName(System.Reflection.MethodInfo method, int index)
      {
          string retVal = string.Empty;
      
          if (method != null && method.GetParameters().Length > index)
              retVal = method.GetParameters()[index].Name;
      
      
          return retVal;
      }
      

      上面的示例应该可以满足您的需求。

      【讨论】:

      • 关于使用参数作为params 数组提供的函数的任何想法?
      猜你喜欢
      • 2010-09-18
      • 2015-10-01
      • 2011-10-09
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多