类库调用Winform组件的方法:
首先在类库中建立一个Logger类如下:
public static class Logger
{
private static int Level = 1;
public static Action<string> action = default;
public static void LogDebug(string msg) {
Log(msg, 1);
}
private static void Log(string msg,int level) {
if (Level <= level) {
Console.WriteLine($"{DateTime.Now}:{msg}");
if (action != default)
{
action.BeginInvoke(msg,null,null);
}
}
}
}
然后在Winfrom端设置action
private void Form1_Load(object sender, EventArgs e)
{
Logger.action = (msg) =>
{
listBox1.Invoke(new Action(() =>
{
listBox1.Items.Add(msg);
}));
};
}
然后类库的代码直接调用:
Logger.LogDebug()