C#将任何方法作为参数传递

记录时,总是会纠缠于字符串文字中.

我通过传递表达式< 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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...