微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/98514.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐