Progress 没有报告function
我有windows form app这是我的代码:
private async void btnGo_Click(object sender, EventArgs e) { Progress labelVal = new Progress(a => labelValue.Text = a); Progress progressPercentage = new Progress(b => progressBar1.Value = b); // MakeActionAsync(labelVal, progressPercentage); await Task.Factory.StartNew(()=>MakeActionAsync(labelVal,progressPercentage)); MessageBox.Show("Action completed"); } private void MakeActionAsync(Progress labelVal, Progress progressPercentage) { int numberOfIterations=1000; for(int i=0;i<numberOfIterations;i++) { Thread.Sleep(10); labelVal.Report(i.ToString()); progressPercentage.Report(i*100/numberOfIterations+1); } }
我得到编译错误,“System.Progress”不包含’Report’的定义,并且没有扩展方法’Report’接受类型’System.Progress’的第一个参数可以找到(你是否缺少using指令或程序集参考?)”
但是如果你看一下Progress类:
public class Progress : IProgress
和IProgress接口有function报告:
public interface IProgress { // Summary: // Reports a progress update. // // Parameters: // value: // The value of the updated progress. void Report(T value); }
我错过了什么?
Progress
使用显式接口实现实现了该方法。 因此,您无法使用Progress
类型的实例访问Report
方法。 您需要将其IProgress
为IProgress
才能使用Report
。
只需将声明更改为IProgress
IProgress progressPercentage = new Progress (b => progressBar1.Value = b);
或使用演员
((IProgress)progressPercentage).Report(i*100/numberOfIterations+1);
我更喜欢以前的版本,后者很尴尬。
如文档中所示,该方法是使用显式接口实现实现的。 这意味着如果您不使用该接口访问该方法,它将被隐藏。
显式接口实现用于在引用接口时使某些属性和方法可见,但在任何派生类中都不可见。 因此,当您使用IProgress
作为变量类型时,您只能“看到”它们,但在使用Progress
时则不会。
试试这个:
((IProgress)progressPercentage).Report(i*100/numberOfIterations+1);
或者,当您只需要引用接口声明中可用的属性和方法时:
IProgress progressPercentage = ...; progressPercentage.Report(i*100/numberOfIterations+1);