1
我有兩個類的控制器和CountDownTimer。帶控制器的項目使用CountDownTimer類引用項目。 CountDownTimer類中有方法(TickUpdate),每當定時器倒計時一秒鐘時,就會調用控制器類中的方法。但由於循環依賴,我無法在CountDownTimer項目中引用控制器項目。C#在循環依賴項中調用未引用項目中的方法
所以我的問題是從倒計時類中調用TickUpdate方法的任何方式?
using SailTimerClassLibrary;
namespace SailTimerUIProject
{
public class Controller : ApplicationContext
{
//Store a reference to the UI
internal frmMain MainUI { get; set; }
private int seconds = 30;
CountDownTimer timer;
public Controller()
{
MainUI = new frmMain(this);
//We can do any necessary checks or changes to the MainUI here before it becomes visible
MainUI.Show();
timer = new CountDownTimer(seconds);
TickUpdate(("" + seconds/60).PadLeft(2, '0') + "m:" + ("" + seconds % 60).PadLeft(2, '0') + "s");
}
internal void TickUpdate(string mmss)
{
MainUI.lblTimer.Text = mmss;
}
internal void StartTimer()
{
timer.StartTimer();
}
}
}
namespace SailTimerClassLibrary
{
public class CountDownTimer : ICountDownTimer
{
private int seconds; // Time in seconds
private int reSetValue; // Time in seconds
public System.Windows.Forms.Timer timer1;
public CountDownTimer(int seconds)
{
this.seconds = seconds;
reSetValue = seconds;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick); // Add Handler(timer1_Tick)
timer1.Interval = 1000; // 1 second
//TickUpdate(("" + seconds/60).PadLeft(2, '0') + "m:" + ("" + seconds % 60).PadLeft(2, '0') + "s");
}
public void timer1_Tick(object sender, EventArgs e)
{
seconds--; // Decrement seconds
if (seconds == 0) // Stop Timer at 0
{
timer1.Stop(); // Stop timer
}
else
{
//TickUpdate(convertSecondToMMSS());
if (seconds % 60 == 0 || seconds >= 1 && seconds <= 10)
{
//TickUpdate(seconds);
}
}
}
public void StartTimer()
{
timer1.Start(); // Start Timer
}
public string convertSecondToMMSS()
{
TimeSpan t = TimeSpan.FromSeconds(seconds);
string str = string.Format("{0:D2}m:{1:D2}s", //{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms
t.Minutes,
t.Seconds);
return str;
}
public void StopTimer()
{
timer1.Stop();
}
public void ResetTimer()
{
timer1.Stop();
seconds = reSetValue;
//parent.TickUpdate(convertSecondToMMSS());
}
public void SetTimer(int seconds)
{
timer1.Stop();
this.seconds = seconds;
reSetValue = seconds;
//parent.TickUpdate(convertSecondToMMSS());
}
}
}
瞭解[events]的時間(http://msdn.microsoft.com/zh-cn/library/aa645739%28v=vs.71%29.aspx)。請注意Timer如何不需要明確知道你,Tick的消費者。與訂閱Timer的Tick事件的方式大致相同,您可以在CountdownTimer上創建自定義事件,並將事件發送到外部世界,而無需關心誰在監聽。 – spender 2014-10-16 17:24:30