如何在c#中获取当前执行方法的参数列表?

时间:2014-02-02 02:41:27

标签: c# reflection out-parameters

我被困住了,假设我有一个方法:

public void InsertEmployee(Employee _employee, out Guid _employeeId)
{
    //My code
    //Current execution is here. 
    //And here I need a list of 'out' parameters of 'InsertEmployee' Method
}

如何实现这一目标?我知道的一种方式

 MethodInfo.GetCurrentMethod().GetParameters()

但是如何仅针对out参数更具体?

3 个答案:

答案 0 :(得分:4)

MethodInfo.GetCurrentMethod().GetParameters().Where(p => p.IsOut)

答案 1 :(得分:3)

MethodInfo.GetCurrentMethod()。GetParameters()返回一个ParameterInfo数组,ParameterInfo有一个属性Attributes - 查看该参数是否有参数。

答案 2 :(得分:3)

// boilerplate (paste into LINQPad)
void Main()
{
     int bar;
     MethodWithParameters(1, out bar);
     Console.WriteLine( bar );
}

void MethodWithParameters( int foo, out int bar ){

bar = 123;
var parameters = MethodInfo.GetCurrentMethod().GetParameters();

foreach( var p in parameters )
{
    if( p.IsOut ) // the important part
    {
        Console.WriteLine( p.Name + " is an out parameter." );
    }
  }
}

IsOut Reference

  

此方法取决于可选的元数据标志。这个标志可以   由编译器插入,但编译器没有义务这样做。

     

此方法使用ParameterAttributes的Out标志   枚举器。