Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get method parameter in an array?

Tags:

c#

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

like image 480
Pit Ming Avatar asked Jan 05 '12 13:01

Pit Ming


People also ask

How do you parameter an array?

To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. Now to use that procedure: int B[100]; zero(B, 100);

How do you input an array as a parameter?

when you write int array[] = {...}; is the same as writing int[] array = {...} You are telling the JVM that you are creating an object of type int[] (array of int) with reference name array . When you want to pass the array as a method parameter you have to write the reference name between brackets.

Can arrays be passed as parameters to methods?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

When you pass an array to a method the method receives?

When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.


1 Answers

You could do something like this:

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

Have a look at the ParameterInfo class.

like image 94
Ray Avatar answered Sep 28 '22 19:09

Ray