我有两个班级的控制器和CountDownTimer。带有控制器的项目使用CountDownTimer类引用项目。我在CountDownTimer类中有方法(TickUpdate),每次计时器倒计时一秒钟时,它会调用控制器类中的方法。但由于循环依赖,我无法在CountDownTimer项目中引用控制器项目。
所以我的问题是,是否可以从倒计时类调用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());
}
}
}
答案 0 :(得分:2)
这里的一些设计问题妨碍了你的能力。
CountDownTimer
应该在这两个项目引用的辅助项目或类库中。这避免了整个循环依赖问题。但是控制器怎么样?!
以及....
CountDownTimer
不应该知道控制器或其他任何事情!它应该暴露控制器可以添加处理程序的某种事件,控制器可以自己更新 。