现在的位置: 首页 > 综合 > 正文

得到当前正在运行的方法或属性名[C#]

2012年06月01日 ⁄ 综合 ⁄ 共 1895字 ⁄ 字号 评论关闭

得到当前正在运行的方法或属性名[C#]  

2012-04-18 22:50:08|  分类: C#|字号 订阅

 
 
得到当前正在运行的方法或属性名[C] - 秒大刀 - 秒大刀 博客

     C/C++在编译时有个__FUNCTION__宏可以获取当前的方法名,而C#中并没有这样的预处理宏,无法在编译时获得函数名信息。但C#中却可以通过反射来在运行时拿到这些信息。MethodBase.GetCurrentMethod().Name就是一个很好的渠道; 而通过指定可忽略的栈深度new StackFrame(0).GetMethod().Name提供了更大的灵活性。

    以上方法在可以方便得到普通函数的名称,但将其用于属性(Property)时,会得到get_Property或set_Property这样被修饰过的名字。如果我们要得到代码中的属性名,需要将签名的get_和set_修饰去掉。当然不能简单的进行Substring(4),否则就无法和用户定义的get_UserMethod方法区分。这是个问题...

public static string GetMethodName()
{
         var method = new StackFrame(1).GetMethod(); // 这里忽略1层堆栈,也就忽略了当前方法GetMethodName,这样拿到的就正好是外部调用GetMethodName的方法信息
         var property = (
                   from p in method.DeclaringType.GetProperties(
                            BindingFlags.Instance |
                            BindingFlags.Static |
                            BindingFlags.Public |
                            BindingFlags.NonPublic)
                   where p.GetGetMethod(true) == method || p.GetSetMethod(true) == method
                   select p).FirstOrDefault();
         return property == null ? method.Name : property.Name;
}

    以上通过将当前MethodInfo和调用者类型中所有的PropertyInfo对应的get或set的MethodInfo进行比对,以鉴别调用者是属性,然后再相应的返回属性名或方法名。
 
 
参考:

2013-1-25

    C# 4.5开始,可以采用CallerMemberName特性来获得调用属性或方法的名称。如此实现INotifyPropertyChanged就简捷多了:

publiceventPropertyChangedEventHandlerPropertyChanged;

// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.

privatevoidNotifyPropertyChanged([CallerMemberName]stringpropertyName ="")
{
if(PropertyChanged!=null)
{
PropertyChanged(this,newPropertyChangedEventArgs(propertyName));
}
}


2013-1-26

    By using Caller Info attributes, you can obtain information about the caller to a method. You can obtain file path of the source code, the line number in the source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.[MSDN]

抱歉!评论已关闭.