c# - 在 KeyValuePair 数组中捕获传入的参数值

标签 c# reflection arguments

我想知道如何在数组中获取方法的传入参数。或者只是动态检索我的参数值。

意思是这样的调用:

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/

相关文章:

c# - EPS 转 JPEG,质量较差

c# - 包含拉丁字符的正则表达式

java - Class.getConstructor 找不到兼容的构造函数

Python替换 float 只​​给出整数

python - 我如何断言该参数仅包含 Python 中列出的整数

c# - 根据现有值更改 dataGridView 中的值

c# - 如何从C#的项目资源文件夹中存储的音频文件中提取文件路径

PHP 反射 : How to know if a ReflectionMethod is inherited?

c# - 反射:递归地搜索字符串值的对象,然后报告路径

javascript - 基于下拉选择的调用函数