【问题标题】:c# defined variables in a method as a list - is it possible?c# 在方法中将变量定义为列表 - 有可能吗?
【发布时间】:2011-09-21 07:12:47
【问题描述】:

在php中,可以将方法定义的变量作为数组获取:

function test($a,$b){
  print_r(
       get_defined_vars()
  );
}

在 C# 中可以吗?

【问题讨论】:

  • get_defined_vars 返回当前作用域内的所有变量,包括参数和全局变量。值得庆幸的是,C# 没有类似的东西。事实上,“作用域”并不是真正存在于运行时的东西,就像它在编译时或 PHP 中那样。你到底想做什么?可能有一个很好的方法......
  • @Kobi - 我有带有很多参数的 WebService 方法,我想将其作为列表传输并在 Web 服务之外验证它们。我不想一次又一次地重新声明它们。户田

标签: c#


【解决方案1】:

类似...

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

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

【讨论】:

  • 据我所知,这甚至不包括变量的名称和值,而是指已编译的代码,其中可能有额外的变量(如 IEnumerator,以及用于示例)
  • +1;可能想将方法参数附加到 ala Christophe's answer
【解决方案2】:

您可以为此使用反射。

如果你想内联,那么你首先需要确定你当前所处的方法。

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

然后你可以检索那个方法的参数:

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

【讨论】:

猜你喜欢
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2011-05-01
  • 1970-01-01
相关资源
最近更新 更多