6

Imagine in a class you got this Method:

float Do(int a_,string b_){}

I'm trying to do something like this:

float Do(int a_, string b_)
{
  var params = GetParamsListOfCurrentMethod(); //params is an array that contains (a_ and b_)
}

Can someone help ?

Why should I want to do thet ?

Imagine you got an Interface:

public Interface ITrucMuch
{
 float Do(int a_,string b_);
 // And much more fct
}

And a lot of classes implementing that interface

And a special class that also implement interface:

public class MasterTrucMuch : ITrucMuch
{
  public floatDo(int a_, string b_) 
  {
    ITrucMuch tm = Factory.GetOptimizedTrucMuch(); // This'll return an optimized trucMuch based on some state
    if(tm != null)
    {
      return tm.Do(a_,b_);
    }
    else
    {
      logSomeInfo(...);
    }

    //do the fallback method
  }

As the interface constains a lot of method and as the first lien of all method are always the same (checking if there is a better interface that the current instance and if so call the same method on the instance) I try to make a method of it.

Thx

Pit Ming
  • 401
  • 2
  • 5
  • 13

5 Answers5

13

You could do something like this:

var parameters = MethodBase.GetCurrentMethod().GetParameters();
foreach (ParameterInfo parameter in parameters)
{
    //..
}

Have a look at the ParameterInfo class.

Ray
  • 45,695
  • 27
  • 126
  • 169
1
var params = GetParamsListOfCurrentMethod();

params is a C# keyword so it can't be used as a variable name as above.

Here's a link on how to use the params keyword http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

And some example code pulled form the article.

public static void UseParams(params int[] list)
{
    for (int i = 0; i < list.Length; i++)
    {
        Console.Write(list[i] + " ");
    }
    Console.WriteLine();
}
user1231231412
  • 1,659
  • 2
  • 26
  • 42
0

you can write your function with dynamic parameter like this:

    protected void Do(params object[] list)
    {
            if (list.Length < 2)
                return;

            int a_=(int)list[0];
            string b_=list[1].ToString();
    }
MRM
  • 435
  • 2
  • 10
0

Use Reflection .NET to get the parameter names for the method.

Using reflection to get method name and parameters

or

http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.aspx

Community
  • 1
  • 1
Robbie Tapping
  • 2,516
  • 1
  • 17
  • 18
0

I don't get it. If you want the param values, and this is the method you need to work with, what about simple doing

protected void Do(int a_, string b_)
{
  var paramValues = new object[]{a_, b_};
}

Do you want a more generic answer? Then you are duplicating questions Can I get parameter names/values procedurally from the currently executing function? and How to get parameter value from StackTrace
And you can't, basically.

Community
  • 1
  • 1
Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29