我启动了一个小应用程序(C#、.Net4、控制台应用程序),这是一个根据规则在家里移动文件的基本想法。
这个应用程序已经发展壮大并变得非常有用。所以我的任务是将它分解成更多可重用的类和更小的项目(类库)。
我有一个通用的“Show”函数,它接受一个字符串和一个 error_level id。基于此,我会以某种颜色将文本输出到我的控制台窗口。当它都在一个大类中时一切都很好,但我想将一个方法移动到它自己的类库中 - 但是,我希望它在处理时向我的 UI(控制台窗口,现在)报告更新。当我将它移到类里面时,显然,类里面我的“显示”方法,中断。
有没有一种方法可以让我的类方法发送的消息返回到我的 UI?它是诸如“打开的配置文件”、“正在处理 12 个新文件”、“成功”之类的消息。
碰巧,UI 获取消息并显示它们,而该方法完成其工作。
目前,它是一个控制台应用程序项目。我的计划是删除工作代码,保留控制台应用程序进行测试,然后将“UI”更改为漂亮的 WPF 桌面应用程序。 (我正在尝试学习 WPF,并决定使用我很久以前开始的一个小项目,并对其进行“皮肤处理”)。
最佳答案
我建议您添加一个接口(interface),在您的 UI 中实现该接口(interface),并将对实现该接口(interface)的类的引用传递给您的新类。
如果您在单线程或多线程中执行工作,这种方法应该有效。
例如界面:
public interface INotify
{
void Notify(string Msg);
}
用户界面:
public class Form1 : INotify
{
// This is the method where you instantiate the new worker process
public void DoSomeWork() {
NewClass Worker = New NewClass(this);
}
public delegate void NotifyDelegate(string Msg);
public void Notify(string Msg)
{
txtLog.Text += Msg + Environment.NewLine;
}
void INotify.Notify(string Msg)
{
this.INotify_Notify(Msg);
}
private void INotify_Notify(string Msg)
{
if (this.InvokeRequired)
{
this.Invoke(new NotifyDelegate(Notify), Msg);
}
else
{
this.Notify(Msg);
}
}
}
和新类(只需调用此类中的通知来发送消息):
public class NewClass
{
private INotify m_Notifier;
private void Notify(string Msg)
{
m_Notifier.Notify(Msg);
}
public NewClass(INotify oNotifier)
{
m_Notifier = oNotifier;
}
}
更新替代实现
将使用静态类的替代实现是实现委托(delegate)。
例如,这里是委托(delegate):
public delegate void NotifyDelegate(string Msg);
这是控制台应用程序的示例静态类:
static class Program
{
private static NotifyDelegate m_Notifier;
static void Main(string[] args)
{
m_Notifier = new NotifyDelegate(Notify);
NewClass oNewClass = new NewClass(m_Notifier);
// Your work code here
}
static void Notify(string Msg)
{
Console.WriteLine(Msg);
}
}
和工作类的修订版:
public class NewClass
{
private NotifyDelegate m_Notifier;
public void Notify(string Msg)
{
m_Notifier.Invoke(Msg);
}
public NewClass(NotifyDelegate oNotifier)
{
m_Notifier = oNotifier;
}
}
关于c# - 从方法返回更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8273816/