C# 如何在派生类中委托方法

yilezhuo1894 yilezhuo1894 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
C# 小白,一个项目中遇到的问题:
这个例子是关于从派生类中调用的实现,虽然没实现.一个 进度条,一个 标签 ,一个按钮,完整(错误)例子如下

窗体:
System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
delegate void AsynUpdateUI(int step);

public Form1()
{
InitializeComponent();
}

private void btnWrite_Click(object sender, EventArgs e)
{
int taskCount = 10000; //任务量为10000
this.pgbWrite.Maximum = taskCount;
this.pgbWrite.Value = 0;

w2 dataWrite = new w2();//实例化一个写入数据的类
dataWrite.UpdateUIDelegate += UpdataUIStatus;//**绑定更新任务状态的委托
dataWrite.TaskCallBack += Accomplish;//**绑定完成任务要调用的委托

//启动线程
//Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write));
Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write));
thread.IsBackground = true;
thread.Start(taskCount);
}

//更新UI
private void UpdataUIStatus(int step)
{
if (InvokeRequired)
{
this.Invoke(new AsynUpdateUI(delegate(int s)
{
this.pgbWrite.Value += s;
this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
}), step);
}
else
{
this.pgbWrite.Value += step;
this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
}
}

//完成任务时需要调用
private void Accomplish()
{
//还可以进行其他的一些完任务完成之后的逻辑处理
MessageBox.Show("任务完成");
}

}
}


父类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WindowsFormsApplication1
{
public class DataWrite
{
protected virtual void Write(object lineCount)
{

}
}
}


子类 w2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WindowsFormsApplication1
{
class w2 : DataWrite
{
public delegate void UpdateUI(int step);//声明一个更新主线程的委托
public UpdateUI UpdateUIDelegate;

public delegate void AccomplishTask();//声明一个在完成任务时通知主线程的委托
public AccomplishTask TaskCallBack;

protected override void Write(object lineCount)
{
StreamWriter writeIO = new StreamWriter("text.txt", false, Encoding.GetEncoding("gb2312"));
string head = "编号,省,市";
writeIO.Write(head);
for (int i = 0; i < (int)lineCount; i++)
{
writeIO.WriteLine(i.ToString() + ",湖南,衡阳");
//写入一条数据,调用更新主线程ui状态的委托
UpdateUIDelegate(1);
}
//任务完成时通知主线程作出相应的处理
TaskCallBack();
writeIO.Close();
}
}
}


主要的问题是实现 从 w2 中通过委托调用 form 的方法,琢磨了一下午,希望高手赐教,谢谢
...全文
评论 3
收藏 已收藏
分享
返回顶部
yilezhuo1894
C# 111,128 成员 642,536 内容