确定用作方法参数的变量的名称 [英] Determine the name of the variable used as a parameter to a method

查看:66
本文介绍了确定用作方法参数的变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何在C#中确定用于调用方法的变量的名称?

How would you, in C#, determine the name of the variable that was used in calling a method?

示例:

public void MyTestMethod1()
{
  string myVar = "Hello World";
  MyTestMethod2(myVar);
}

public void MyMethod2(string parm)
{
  // do some reflection magic here that detects that this method was called using a variable called 'myVar'
}

我知道该参数可能并不总是一个变量,但是我使用它的地方是在一些验证代码中,我希望开发人员可以明确声明他们正在验证的值的友好名称,如果他们不只是从他们用...调用方法的变量名中推断出它.

I understand that the parameter might not always be a variable, but the place I am using it is in some validation code where I am hoping that the dev can either explicitly state the friendly name of the value they are validating, and if they don't then it just infers it from the name of the var that they called the method with...

推荐答案

不幸的是,即使不是没有可能,这也会非常困难.

Unfortunately, that's going to be very hard, if not impossible.

为什么您确切需要最初发送的变量的名称?

Why exactly do you need the name of the variable originally sent in?

请记住,可能没有实际使用的变量:

Remember that there might not be an actual variable used:

MyMethod2(myVar + "! 123");

在这种情况下,myVar仅保留部分值,其余部分在运行时在表达式中计算.

In this case, myVar holds just parts of the value, the rest is calculated in the expression at runtime.

这篇关于确定用作方法参数的变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆