我想知道如何在数组中获取方法的传入参数。或者只是动态检索我的参数值。
意思是这样的调用:
MyMethod(10, "eleven");
对于方法:
void MyMethod(int Test, str Test2) {}
将解析为如下数组:
{{"Test" => 10}, {"Test2", "eleven"}}
如果我能通过反射实现这一点,那就更好了。例如。以某种方式使用 StackTrace。
最佳答案
我想,你要找的东西不存在。最接近的是参数:
MyMethod(params object[] args)
{
// if you have to do this, it's quite bad:
int intArg = (int)args[0];
string stringArg = (string)arg[1]:
}
// call with any number (and type) of argument
MyMethod(7, "tr");
没有编译时类型检查,因此它不是处理参数的通用方法。但如果您的论点是动态的,它可能是一个解决方案。
编辑:有另一个想法:
您需要将所有参数手动放入列表/字典中。您可以编写一个帮助程序类以允许执行以下操作:
MyMethod(int arg1, string arg2)
{
Arguments.Add(() => arg1);
Arguments.Add(() => arg2);
//
}
助手看起来像这样
public static void Add<T>(Expression<Func<T>> expr)
{
// run the expression to get the argument value
object value = expr.Compile()();
// get the argument name from the expression
string argumentName = ((MemberExpression)expr.Body).Member.Name;
// add it to some list:
argumentsDic.Add(argumentName, value);
}
关于c# - 在 KeyValuePair 数组中捕获传入的参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/833489/