【发布时间】:2018-11-14 12:17:57
【问题描述】:
我有这个 Logger 类:
public static class Logger
{
public static void LogError(Exception e)
{
}
public static void TryCatchLogError<T>(this T item, Action action)
{
try
{
action();
}
catch (Exception ex)
{
LogError(ex);
}
}
}
我可以这样做:
public partial class Form1 : Form
{
public void GetBreakDownMachine()=> this.TryCatchLogError(() =>
{
{
//my code
}
});
}
但不能在我的静态主类中做同样的事情
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()=> this.TryCatchLogError(() =>
{
{
//my code
}
});
}
我怎样才能为上述静态方法使用 Logger 扩展类?
【问题讨论】:
-
"item" 参数是引发异常的对象。我在这里删除了它的用法,因为它包含敏感内容。
-
[STAThread] static void Main() => Logger.TryCatchLogError<Program>(null, () => { Console.WriteLine("bob"); });您不能在static方法的上下文中使用this.,因为它没有意义 - 没有实例可言。 -
多么愚蠢,我错过了为班级删除静态。我又坏了。我以前也尝试过你的建议,但正如所说,错过了让课程成为非静态的。它现在有效,现在我也明白了@theGeneral 的答案。谢谢
标签: c# exception logging try-catch