C# 学员:向上层通知操作
这个问题与c#有关。场景是,当我单击按钮时,将发生文件读取、数据操作和文件转储等操作。完成每个操作后,我将更新UI(表单frmTesting)中标签中的状态(即文件读取完成、数据操作完成) 按钮单击事件为C# 学员:向上层通知操作,c#,winforms,delegates,C#,Winforms,Delegates,这个问题与c#有关。场景是,当我单击按钮时,将发生文件读取、数据操作和文件转储等操作。完成每个操作后,我将更新UI(表单frmTesting)中标签中的状态(即文件读取完成、数据操作完成) 按钮单击事件为 namespace frmTesting { public partial class Form1 : Form { private void button1_Click_1(object sender, EventArgs e) {
namespace frmTesting
{
public partial class Form1 : Form
{
private void button1_Click_1(object sender, EventArgs e)
{
class1 l_objClass1 = new class1();
l_objClass1.DoOperation();
}
}
public class class1
{
public int DoOperation()
{
ReadTextFile();
ParsingData();
SaveTextFile();
return 0;
}
private int ReadTextFile()
{
//Read the text File
return 0;
}
private int ParsingData()
{
// Data manipulation
return 0;
}
private int SaveTextFile()
{
// save the file
return 0;
}
}
}
是否可以使用代理进行此操作?当然可以
您可以在Class1上设置委托属性
创建Class1(或者可以在构造函数中执行此操作)后,将函数分配给委托属性
当您的操作发生/完成时,他们会检查委托是否为null,然后使用他们想要的任何事件参数(状态级别、完成状态等)执行委托
然后,传递给委托的Form1函数将处理参数的处理,并为文本字段赋值。这是
属性的一个非常糟糕的用法。请改用方法
。您不应该依赖属性执行特定代码或特定操作(这里是日志记录)。这只是一个糟糕的做法。不,这是标准做法。属性作者不知道要运行多少代码或什么类型的代码。它不在他的控制之下。根据我对上述代码的解释,您将得到递归,就像调用委托时一样,被调用的每个子方法将依次设置“s”属性,从而一次又一次地重新调用它。。。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WindowsFormsApplication3
{
public delegate void MyDelagate();
class Class1
{
public event MyDelagate _myDelegate;
private String s1 = String.Empty;
public String s
{
get
{
return s1;
}
set
{
s1 = value;
if(_myDelegate != null)
_myDelegate();
}
}
public int DoOperation()
{
s = "Started";
ReadTextFile();
ParsingData();
SaveTextFile();
s = "Completed";
return 0;
}
private int ReadTextFile()
{
s = "Read Text File";
Thread.Sleep(3000);
return 0;
}
private int ParsingData()
{
s = "Parsing Data";
Thread.Sleep(3000);
return 0;
}
private int SaveTextFile()
{
s = "Save Text File";
Thread.Sleep(3000);
return 0;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
Class1 x = new Class1();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
x._myDelegate += new MyDelagate(UpdateStatus);
x.DoOperation();
}
void UpdateStatus()
{
label1.Text = x.s;
Validate();
}
}
}