我想将变量(Swt,Srt)从设置表单传递到 Main,并使用它们。问题是当程序启动时,WorkDelay 和 RecreationDelay 被创建为空,以后不会改变。
public static int Swt, Srt;
public TimeSpan WorkDelay = TimeSpan.FromMinutes(Swt); //Work time in minutes
public TimeSpan WorkDelay = TimeSpan.FromMinutes(Swt); //Work time in minutes
主要形式
public partial class Main : Form
{
private DateTime _globalTimeDate;
public static int Swt, Srt;
private DateTime _workExpiry;
public TimeSpan WorkDelay = TimeSpan.FromMinutes(Swt); //Work time in minutes
private DateTime _recreationExpiry;
public TimeSpan RecreationDelay = TimeSpan.FromMinutes(Srt); // Recreation time in minutes
public Main()
{
InitializeComponent();
stop.Enabled = false;
global.Text = @"Stoped";
work.Text = @"Stoped";
recreation.Text = @"Stoped";
}
private void globalTimer_Tick(object sender, EventArgs e)
{
long tick = DateTime.Now.Ticks - _globalTimeDate.Ticks;
DateTime stopWatch = new DateTime();
stopWatch = stopWatch.AddTicks(tick);
global.Text = $@"{stopWatch:HH:mm:ss}";
}
private void workTimer_Tick(object sender, EventArgs e)
{
TimeSpan remaining = _workExpiry - DateTime.Now;
work.Text = remaining.ToString("hh\\:mm\\:ss");
if (work.Text == @"00:00:00")
{
workTimer.Stop();
work.Text = @"Stoped, start recreation";
_recreationExpiry = DateTime.Now.Add(RecreationDelay);
recreationTimer.Start();
}
}
private void recreationTimer_Tick(object sender, EventArgs e)
{
TimeSpan remaining = _recreationExpiry - DateTime.Now;
recreation.Text = remaining.ToString("hh\\:mm\\:ss");
if (recreation.Text == @"00:00:00")
{
recreationTimer.Stop();
recreation.Text = @"Stoped, strart work";
_workExpiry = DateTime.Now.Add(WorkDelay);
workTimer.Start();
}
}
private void start_Click(object sender, EventArgs e)
{
_globalTimeDate = DateTime.Now;
_workExpiry = DateTime.Now.Add(WorkDelay);
globalTimer.Start();
workTimer.Start();
start.Enabled = false;
stop.Enabled = true;
}
private void stop_Click(object sender, EventArgs e)
{
globalTimer.Stop();
workTimer.Stop();
recreationTimer.Stop();
work.Text = @"Stoped";
recreation.Text = @"Stoped";
stop.Enabled = false;
start.Enabled = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
globalTimer.Stop();
workTimer.Stop();
recreationTimer.Stop();
Application.Exit();
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
Settings settings = new Settings();
settings.Show();
}
}
}
设置表格
public partial class Settings : Form
{
public Settings()
{
InitializeComponent();
}
private void buttonSet_Click(object sender, EventArgs e)
{
try
{
Main.Swt = (int) Convert.ToDouble(textBoxW.Text.Replace(',', '.'));
Main.Srt = (int) Convert.ToDouble(textBoxR.Text.Replace(',', '.'));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Close();
}
private void buttonReset_Click(object sender, EventArgs e)
{
Main.Swt = 0;
Main.Srt = 0;
}
}
}
制作字段
...Delay
属性并在访问这些属性时计算其值。它将解决一个问题——“不要进一步改变”。在 C# 6 中(节省花括号墨水):
关于“被创造为空”。这是因为 和 的初始值
Swt
为零Srt
。为它们分配一些非零值:附言
问题:为什么
Swt
和Srt
- 静态,WorkDelay
和RecreationDelay
- 对象字段?思考。