Finding the variable name passed to a function
Let me use the following example to explain my question:
public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World"';
string Hello = ExampleFunction(WhatIsMyName);
When I pass the variable "WhatIsMyName" to the example function, I want to be able to get a string of the original variables name. Perhaps something like:
Variable.OriginalName.ToString()
Is there any way to do this?
**No.**I don't think so.
The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken.
If it helps, you could define a new class called NamedParameter with attributes Name and Param. You then pass this object around as parameters.
What you want isn't possible directly but you can use Expressions in C# 3.0:
public void ExampleFunction(Expression<Func<string, string>> f) {
Console.WriteLine((f.Body as MemberExpression).Member.Name);
}
ExampleFunction(x => WhatIsMyName);
Note that this relies on unspecified behaviour and while it does work in Microsoft's current C# and VB compilers, and in Mono's C# compiler, there's no guarantee that this won't stop working in future versions.
I know this is an old question but in C# 6.0 they Introduce the nameof Operator which should solve this issue. The name of operator resolves the name of the variable passed into it.
Usage for your case would look like this:
public string ExampleFunction(string variableName) {
//Construct your log statement using c# 6.0 string interpolation
return $"Error occurred in {variableName}";
}
string WhatIsMyName = "Hello World"';
string Hello = ExampleFunction(nameof(WhatIsMyName));
A major benefit is that it is done at compile time,
The nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an "unreachable code" warning).
More information can be found here
Older Version Of C 3.0 and above
To Build on Nawfals answer
GetParameterName2(new { variable });
//Hack to assure compiler warning is generated specifying this method calling conventions
[Obsolete("Note you must use a single parametered AnonymousType When Calling this method")]
public static string GetParameterName<T>(T item) where T : class
{
if (item == null)
return string.Empty;
return typeof(T).GetProperties()[0].Name;
}
链接地址: http://www.djcxy.com/p/69024.html
上一篇: 如何使用反射获取变量名称?
下一篇: 查找传递给函数的变量名称