记录时,总是会纠缠于字符串文字中.
我通过传递表达式< Func< T>>来很好地解决了属性,字段和变量.表达式(如here所述),所以你可以做这样的事情:
public void Demo(string someArgument) { LogFrameWork.LogLine("Demo"); // goal is to get rid of these string literals LogFramework.Log(() => someArgument); }
我想为Demo本身做一些类似的事情:
public void Demo(string someArgument) { LogFramework.Log(this.Demo); }
我尝试过这样的事情:
public static void Log(Delegate method) { string methodName = method.Method.Name; LogLine(methodName); }
还有这个:
public static void Log(Action method) { string methodName = method.Method.Name; LogLine(methodName); }
但我得到这样的编译器错误:
Argument 1: cannot convert from 'method group' to 'System.Delegate' Argument 1: cannot convert from 'method group' to 'System.Action'
我可以使用Func<…>和Action<…>引入一堆重载,但听起来过于复杂.
对于任何具有任意数量参数和可选结果的方法,有没有办法覆盖这个?
–jeroen
PS:我认为this question可能在这里有一些相关性,但没有答案让我感到’aha’的感觉:-)
解决方法
而不是尝试将方法作为参数传递给记录器,而是从使记录器识别调用方法的角度来看它.
这是一个(伪)示例:
记录器类
public void Debug( string message ) { message = string.Format( "{0}: {1}",GetCallingMethodInfo(),message ); // logging stuff } /// <summary> /// Gets the application name and method that called the logger. /// </summary> /// <returns></returns> private static string GetCallingMethodInfo() { // we should be looking at the stack 2 frames in the past: // 1. for the calling method in this class // 2. for the calling method that called the method in this class MethodBase method = new StackFrame( 2 ).GetMethod(); string name = method.Name; string type = method.DeclaringType.Name; return string.Format( "{0}.{1}",type,name ); }
使用记录器的任何地方:
// resides in class Foo public void SomeMethod() { logger.Debug("Start"); }
然后记录器的输出为:Foo.SomeMethod:Start