返回循环进度的方法
本文关键字:方法 循环 返回 | 更新日期: 2023-09-27 18:30:42
我正在使用一种方法创建一个类库,例如OnetoTen(),它基本上是一个从1到10的for循环计数。我试图实现的是从另一个程序调用此方法,并让它输出 for 循环当前的数量/迭代次数。
使用代表/活动是正确的方法吗?
您可以使用回调(委托)或事件。
使用回调的示例:
class Program
{
static void Main(string[] args)
{
var counter = new Counter();
counter.CountUsingCallback(WriteProgress);
Console.ReadKey();
}
private static void WriteProgress(int progress, int total){
Console.WriteLine("Progress {0}/{1}", progress, total);
}
}
public class Counter
{
public void CountUsingCallback(Action<int, int> callback)
{
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(1000);
callback(i + 1, 10);
}
}
}
使用事件的示例:
class Program
{
static void Main(string[] args)
{
var counter = new Counter();
counter.ProgessTick += WriteProgress;
counter.CountUsingEvent();
Console.ReadKey();
}
private static void WriteProgress(int progress, int total){
Console.WriteLine("Progress {0}/{1}", progress, total);
}
}
public class Counter
{
public event Action<int, int> ProgessTick;
public void CountUsingEvent()
{
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(1000);
if (ProgessTick != null)
ProgessTick(i + 1, 10);
}
}
}