Today in the self-regulatory process design, the variable name matching string from the configuration file, the Internet for a while found a friend is looking for this way, it is not easy to find a solution from http://www.th7.cn/Program/net/201404/187358.shtml
Here's what we found today for a detailed answer.
You first need to customize a static method
/// <summary> ///Extended Get variable name (string)/// </summary> /// <param name= "Var_name" ></param> /// <param name= "exp" ></param> /// <returns>return string</returns> Public Static stringGetvarname<t> ( ThisT Var_name, System.linq.expressions.expression<func<t, t>>exp) { return((System.Linq.Expressions.MemberExpression) exp. Body). Member.name; }
The above is for the convenience of the call so the use of the extension does not like the friend can use the following method can be directly written in the tool class
/// <summary> ///Get variable name/// </summary> /// <param name= "exp" ></param> /// <returns>return String</returns> Public Static stringGetvarname<t> (System.linq.expressions.expression<func<t, t>>exp) { return((System.Linq.Expressions.MemberExpression) exp. Body). Member.name; }
The following is an extended call demo
bool Test_name = true; Variable types can be arbitrarily
String tips = Test_name. Getvarname (it = test_name);
Execution can only be the variable you want to return, the local variable arbitrarily. Cannot write other error in anonymous method. (The following error shows) bool test_name = true;
String tips = Test_name. Getvarname (it = 1==1); Many experienced it friends should also discover the principle of implementation, using the LAMDA expression. The above call seems to have a little excess of parameters, personal habits. The following is a non-extensible call to demonstrate bool Test_name = true;
String tips = Class name. Getvarname (it test_name); it looks as if the difference with the above is only to point out the method, so this depends on personal habits personally think in it or rookie, the first time I wrote a blog, I did not say, the above tested, not tested completely. Those who wish to have other opinions, correct me!
"Unpopular" C # tips for getting variable names