【转】 C# 小技巧之获取变量名称

link: http://www.cnblogs.com/gongy/p/lm-2015-04-03.html

今天在自我规范程序设计的时候,变量名匹配字符串来自配置文件,网上找了一会儿发现也有朋友在找寻这种方式,很不容易找到一个解决方案来自http://www.th7.cn/Program/net/201404/187358.shtml

下面就是今天找到的进行详细解答

首先需要自定义一个静态方法

     

/// <summary>

///扩展获取变量名称(字符串)

/// </summary>

/// <param name="var_name"></param>

/// <param name="exp"></param>

/// <returns>return string</returns>

public static string GetVarName<T>(this T var_name, System.Linq.Expressions.Expression<Func<T, T>> exp)

{

return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;

}

以上是为了调用方便所以使用了扩展不喜欢的朋友可以用下方的方式 方法可以直接写工具类中

/// <summary>

///获取变量名称

/// </summary>

/// <param name="exp"></param>

/// <returns>return string</returns>

public static string GetVarName<T>(System.Linq.Expressions.Expression<Func<T, T>> exp)

{

return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;

}

下面是扩展的调用演示

      bool test_name = true; //变量类型可随意
      string tips = test_name.GetVarName(it => test_name);//返回结果 “test_name“

执行只能是你要返回变量,局部变量随意。

 

不能在匿名方法里写其它否则报错。

(以下错误演示)

      bool test_name = true;
      string tips = test_name.GetVarName(it => 1==1);

很多有经验的IT朋友应该也发现了实现原理,利用了lambda表达式。

上述调用看起来参数有点过剩,个人习惯。

   

下面是非扩展的调用演示

     bool test_name = true;
     string tips =
类名.GetVarName(it => test_name);

看起来好像跟上面的区别也仅是用什么点出这个方法,所以这个就得看个人习惯

希望有其它意见的朋友指正!

问题:

         string tips = test_name.GetVarName(it => test_name);//返回结果 “test_name“

调用过于复杂和冗余,能否改成

   string tips = test_name.GetVarName();//返回结果 “test_name“

标签C#获取变量名称

原文地址:https://www.cnblogs.com/xiexiaokui/p/5143749.html