How to get a method parameter in an array?

Imagine that in a class you got this method:

float Do(int a_,string b_){} 

I am 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 anyone help?

Why should I do this?

Imagine you have an interface:

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

And many classes implementing this interface

And a special class that also implements the 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 } 

Since the interface contains many methods, and since the first lien of all methods is always the same (checking if there is a better interface which is the current instance and if it calls the same method in the instance), I am trying to make its method.

thanks

+4
source share
5 answers

You can do something like this:

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

Take a look at the ParameterInfo class.

+11
source
 var params = GetParamsListOfCurrentMethod(); 

params is a C # keyword, so it cannot be used as a variable name, as mentioned above.

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

And pulled some sample code from the article.

 public static void UseParams(params int[] list) { for (int i = 0; i < list.Length; i++) { Console.Write(list[i] + " "); } Console.WriteLine(); } 
+1
source

you can write your function with a dynamic parameter as follows:

  protected void Do(params object[] list) { if (list.Length < 2) return; int a_=(int)list[0]; string b_=list[1].ToString(); } 
0
source

I do not understand. If you need parameter values, and this is the method you need to work with, what to do with simple execution

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

Do you want a more general answer? Then you duplicate the questions. Can I get parameter names / values ​​procedurally from the current executable function? and How to get parameter value from StackTrace
And you can’t, basically.

0
source

Source: https://habr.com/ru/post/1389469/


All Articles