Kev*_*inT 2 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 called 'myVar'
}
Run Code Online (Sandbox Code Playgroud)
我知道参数可能并不总是变量,但我使用它的地方是在一些验证代码中,我希望开发人员可以明确说明他们验证的值的友好名称,如果他们不'然后它只是从他们称之为方法的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"
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,所有调用都必须包含在lambdas中,如果您在lambda中开始执行任何其他操作,除了返回单个变量之外,此方法也会崩溃.