开发者

c# defined variables in a method as a list - is it possible?

开发者 https://www.devze.com 2023-04-06 13:31 出处:网络
In php, you can get the method\'s defined variables as an array: function test($a,$b){ print_开发者_开发知识库r(

In php, you can get the method's defined variables as an array:

function test($a,$b){
  print_开发者_开发知识库r(
       get_defined_vars()
  );
}

Is it possible in C#?


Something like...

string a = "hello";
int b = 20;
DateTime c = DateTime.Now;

foreach (LocalVariableInfo variable in MethodInfo.GetCurrentMethod().GetMethodBody().LocalVariables)
{
    Console.WriteLine(variable);
}


You can use reflection for this.

If you want to do this inline, then you first need to determine the method you are currently in.

var currentMethod = System.Reflection.MethodInfo.GetCurrentMethod();

Then you can retrieve the parameters of that method:

foreach(ParameterInfo parameter in currentMethod.GetParameters())
{
    var name = parameter.Name;
    //...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消