gpt4 book ai didi

c# - 日志管理器类可供所有类访问

转载 作者:行者123 更新时间:2023-12-03 07:54:52 25 4
gpt4 key购买 nike

我已经为此苦苦挣扎了一段时间……我有一个使用MVP模式编写的程序,我想拥有一个LogHandler类,该类必须检索对应于这些方法之一提供的ID的字符串,但是它也需要更新GUI,将项目添加到列表框中。因此,简单地想象一下:

if (name != "Peter")
{
Log.RegisterError(31, 4) //errorType, errorID
}

因此,在Log类中,它将获得与提供的类型和ID相匹配的字符串,并在MessageBox中获得与之匹配的字符串,但是如果我想将该字符串添加到表单上的控件中怎么办?我正在使用由表单实现的 View 来完成GUI更新,但是由于这是静态类,所以我不能...

另外,应该在哪里检查并提出错误?主持人? View ?模型?

提前致谢

最佳答案

您可以在Log类中添加其他对象可以订阅的回调。

例:

在此示例中,Presenter可以侦听要记录的错误代码,然后从Model类的Log接收错误字符串。

public class Logger
{
private static Dictionary<int, List<Action<string>>> _callbacks = new Dictionary<int,List<Action<string>>>();

public static void RegisterLoggerCallback(int errorType, Action<string> callback)
{
// Just using errortype in this exaple, but the key can be anything you want.
if (!_callbacks.ContainsKey(errorType))
{
_callbacks.Add(errorType, new List<Action<string>>());
}
_callbacks[errorType].Add(callback);
}

public static void RegisterLog(int errorType, int errorID)
{
// find error sring with codes
string error = "MyError";

// show messagebox
MessageBox.Show(error);

// tell listeners
if (_callbacks.ContainsKey(errorType))
{
_callbacks[errorType].ForEach(a => a(error));
}
}
}

public class Model
{
public Model()
{
}

public void DoSomething()
{
Logger.RegisterLog(1, 2);
}
}

public class Presenter
{
public Presenter()
{
Logger.RegisterLoggerCallback(1, AddToListbox);
}

private void AddToListbox(string error)
{
// add to listbox when errortype 1 is called somewhere
}
}

这是一个非常简单的示例,但应为您提供一种实现此目的的方法。

关于c# - 日志管理器类可供所有类访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com