我正在創建一個類庫的方法,例如,OnetoTen(),它基本上是一個for循環計數從1到10.我想要實現的是調用此方法從另一個程序,並讓它輸出for循環當前所處的數字/迭代。方法返回循環的進度
使用代表/事件的正確方法是什麼?
我正在創建一個類庫的方法,例如,OnetoTen(),它基本上是一個for循環計數從1到10.我想要實現的是調用此方法從另一個程序,並讓它輸出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);
}
}
}
謝謝,但是我應該什麼時候選擇哪個變體?有沒有任何指導方針? – KnorxThieus
在這種情況下,我寧願回調。我認爲,如果您不知道您是否會有多少用戶,那麼事件會更好。這個例子看起來總是隻有一件事需要通知。 –
非常感謝! – KnorxThieus
- 它可能是,取決於你真正的意思是「有輸出」。請注意,「輸出」可能意味着很多不同的事情:顯示到控制檯,更新屏幕上的文本,寫入文件等。您已經收到一個答案,演示使用委託,作爲顯式回調對象和作爲事件訂閱者(事件只是一個抽象成員,允許將委託實例添加到回調代理鏈中)。如果這不是你想要的,你需要更清楚明確地寫出你的問題。 –
彼得,感謝您的反饋,我一定會把它帶上! – LuxC