Progress<T>没有Report函数。

29
我有一个Windows表单应用程序,这是我的代码:

  private async void btnGo_Click(object sender, EventArgs e)
    {
        Progress<string> labelVal = new Progress<string>(a => labelValue.Text = a);
        Progress<int> progressPercentage = new Progress<int>(b => progressBar1.Value = b);

       // MakeActionAsync(labelVal, progressPercentage);
        await Task.Factory.StartNew(()=>MakeActionAsync(labelVal,progressPercentage));
        MessageBox.Show("Action completed");
    }

    private void MakeActionAsync(Progress<string> labelVal, Progress<int> 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'的定义,也没有接受类型为'System.Progress'的第一个参数的扩展方法'Report'(您是否缺少使用指令或程序集引用?)”
但是,如果您查看Progress类:
public class Progress<T> : IProgress<T>

接口 IProgress 具有 Report 功能:

  public interface IProgress<in T>
{
    // Summary:
    //     Reports a progress update.
    //
    // Parameters:
    //   value:
    //     The value of the updated progress.
    void Report(T value);
}

我错过了什么?

2个回答

37

Progress<T> 采用显式接口实现的方式实现了该方法。因此你不能使用类型为 Progress<T> 的实例访问 Report 方法。你需要将其转换为 IProgress<T> 才能使用 Report 方法。

只需将声明更改为 IProgress<T>

IProgress<int> progressPercentage = new Progress<int>(b => progressBar1.Value = b);

或者使用一个转换

((IProgress<int>)progressPercentage).Report(i*100/numberOfIterations+1);

我更喜欢前一个版本,后一个版本不太自然。


“显式接口实现”是什么意思?接口方法在子类中不可见吗? - ilay zeidman
这样做的原因是鼓励您的方法接受 IProgress 参数而不是 Progress(消除了显式转换的需要)。这使得调用者可以提供自己的 IProgress 实现。 - Bip901

6
文档所示,该方法是使用显式接口实现来实现的。这意味着如果您不使用接口访问该方法,则该方法将被隐藏。
显式接口实现用于在引用接口时使某些属性和方法可见,但在任何派生类中都不可见。因此,只有当您将IProgress<T>作为变量类型时才能“看到”它们,而不能在使用Progress<T>时看到它们。
请尝试此操作:
((IProgress<string>)progressPercentage).Report(i*100/numberOfIterations+1);

当您仅需要引用接口声明中可用的属性和方法时:

IProgress<string> progressPercentage = ...;

progressPercentage.Report(i*100/numberOfIterations+1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接