C# 确定用作方法参数的变量的名称
在C#中,如何确定调用方法时使用的变量的名称 例如:C# 确定用作方法参数的变量的名称,c#,reflection,parameters,C#,Reflection,Parameters,在C#中,如何确定调用方法时使用的变量的名称 例如: 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 call
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'
}
我知道参数可能并不总是一个变量,但我使用它的地方是在一些验证代码中,我希望开发人员可以显式地声明他们正在验证的值的友好名称,如果他们不这样做,那么它只是从他们调用方法的var的名称中推断出来…不幸的是,这将非常困难,如果不是不可能的话 为什么您需要最初发送的变量的名称 请记住,可能没有实际使用的变量:
MyMethod2(myVar + "! 123");
在这种情况下,myVar只保存部分值,其余值在运行时在表达式中计算。变量是为实体分配语义的方便标识符。以编程的方式描述它们似乎是一种很大的代码味道。此外,如果知道这一点真的很重要,你就不能传入第二个参数吗
编辑:OP更新了他的问题,包括以下内容: 我知道参数可能并不总是一个变量,但我使用它的地方是在一些验证代码中,我希望开发人员可以明确说明他们正在验证的值的友好名称,如果他们没有,那么它只是从他们调用方法的var的名称中推断出来
如果它们显式地声明了它,并且这对您很重要,那么它肯定应该作为参数传递给函数。有一种方法,但它非常难看
public void MyTestMethod1()
{
string myVar = "Hello World";
MyTestMethod2(() => myVar);
}
public void MyMethod2(Expression<Func<string>> func)
{
var localVariable = (func.Body as MemberExpression).Member.Name;
// localVariable == "myVar"
}
public void MyTestMethod1()
{
字符串myVar=“Hello World”;
MyTestMethod2(()=>myVar);
}
公共void MyMethod2(表达式函数)
{
var localVariable=(func.Body作为MemberExpression).Member.Name;
//localVariable==“myVar”
}
如您所见,所有调用都必须包装到lambda中,如果您在lambda中除了返回单个变量外还开始执行任何其他操作,则此方法将崩溃。我觉得您应该使用枚举作为变量的标识符,而不是试图确定变量的名称。变量的全部意义在于,它只是一个人类可读的名称来表示一点内存 你可以做:
public void MyTestMethod1()
{
string myVar = "Hello World";
MyTestMethod2(myVar, VariableType.MyVar);
}
public void MyMethod2(string parm, VariableType type)
{
if (type == VariableType.MyVar)
{
}
}
可能重复的