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

c# – 从类中添加项目到日志窗口的最佳方法

我正在尝试将类中的“日志”消息添加到表单上的ListBox中.在表单中我只能使用lblog.add(“message”),但是当我正在尝试清理我的代码时,将“消息”传递给前端的最佳方法是什么?

我发现了一个有下面代码的建议,但想知道是否有更简单的方法

形成:

// This is all required so that we can call the function from another class 
public void publicLogMessage(string message)
{
    if (Invokerequired)
    {
        Invoke(new OutputDelegate(logMessage),message);
    }
}

public delegate void OutputDelegate(string message);

public void logMessage(string message)
{
    lblog.Items.Add(DateTime.Now + "  " + message);
}

类:

//This is required so that we can call the "PublicLogMessage" function on the main form
public frmMain formToOutput;

public speechRecognition(frmMain f)
{
    formToOutput = f;
}

用法

formToOutput.logMessage

解决方法

您现在在算法和输出方法之间存在非常紧密的耦合.您的算法知道您的输出方法的所有内容(例如,它是具有特定签名的表单).

我建议将它解耦:

private readonly Action<string> log;    

public speechRecognition(Action<string> log)
{
    this.log = log;
}

public void DoWork()
{
   this.log("work started");

   // ...

   this.log("work in progress");

   // ...

   this.log("work ended");
}

这个类对日志记录方法一无所知.它只知道它得到一个字符串.控制输出方法(表单)和算法(上面的类)的类可以将它们链接在一起:

var form = new YourFormWithLoggingWindow();

var algorithm = new speechRecognition(form.publicLogMessage);

现在算法将登录到表单.你可以用它来调用

var algorithm = new speechRecognition(Console.WriteLine);

它将在控制台应用程序中登录到控制台.该算法不关心,也不需要您的表单进行编译.它是独立的.您的表单也不知道算法.它也是独立的.

您甚至可以进行单元测试来检查日志记录:

var log = new List<string>();
var algorithm = new speechRecognition(log.Add);

algorithm.DoWork();

Assert.AreEqual(log.Count,3);

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

相关推荐