0

How do you declare a progress bar as an optional parameter?

Here is the function:

public int Factorial(int number, System.Windows.Forms.Label l, System.Windows.Forms.ProgressBar newprogressbar, int time=0)
    {

      ....

    }

The function has four parameters. Only int number and the label l should be mandatory. time is already optional, but I don't know how to make the new progressbar optional. The function returns the factorial of a number and it's uses a label to display it.

The progress bar should show the state of the stack and the time should be the speed at which the function works, but these two should be optional.

I have already done the function, but I still need to figure out how to make the progressbar optional.

4

2 回答 2

3

与您将任何其他参数声明为可选的相同方式 - 您指定一个默认值。但是,默认值必须是一个常量,这对于除string基本类型之外的引用类型意味着null

public int Factorial(int number, Label l, ProgressBar newProgressBar = null,
                     int time = 0) {

但是,就我个人而言,我会更改设计。您可以传入一个委托,而不是Factorial同时了解“如何计算阶乘值”和“如何显示进度”:

public int Factorial(int number, Action<int> progressAction, int time = 0) {

...然后在循环的每次迭代中调用该进度操作(我假设您使用进度条执行此操作)。

这改善了关注点的分离。如果您不想在所有情况下都显示进度,则可以将progressAction默认设置为null.

另一种选择是完全反转控件,并Factorial仅将其视为一系列值 - 使用迭代器块轻松完成此操作:

public IEnumerable<int> Factorial()
{
    for (...)
    {
        // Do work
        yield return currentValue;
    }
}

您可以分别施加时间限制(我假设这是time参数的用途?),这样调用者就可以计算出迭代多少次以及如何处理结果。该Factorial方法知道如何产生一个阶乘数序列。

于 2012-07-27T06:26:04.140 回答
0

ProgressBar 最终派生自 System.Object,因此您只需编写

public int Factorial(int number, System.Windows.Forms.Label l, 
    System.Windows.Forms.ProgressBar newprogressbar = null, int time=0)

要检查方法是否已定义,只需编写

if (newprogressbar != null)
{
    // Do something with newprogressbar
}
于 2012-07-27T06:24:23.743 回答