C# 打卡/打卡小时 - 总工作时间
C# Clock In / Clock Hour - Total Time Worked
问题:创建一个由打卡按钮、打卡按钮和标签组成的程序来保存总工作时间。
这段代码看起来应该很简单,但我知道我遗漏了一些东西。我无法从 inButton 单击获取 DateTime clockIn 以在 outButton 单击中与 TimeSpan 一起使用。我是 C# 的新手,所以欢迎任何批评。谢谢!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TimeClock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inButton_Click(object sender, EventArgs e)
{
DateTime clockIn = DateTime.Now;
}
public void outButton_Click(object sender, EventArgs e)
{
DateTime clockOut = DateTime.Now;
TimeSpan timeWorked = clockOut - clockIn;
string timeWorkedReport = $"Time worked = {timeWorked.Hours} hours, {timeWorked.Minutes} minutes";
timeLabel.Text = timeWorkedReport;
}
}
}
最重要的是,您需要阅读有关变量范围和数据成员的内容。
不太重要 - 以下将起作用:
我刚刚将您的变量提升为 Class 数据成员。
public partial class Form1 : Form
{
DateTime clockIn = DateTime.Min; // Move Here
public Form1()
{
InitializeComponent();
}
public void inButton_Click(object sender, EventArgs e)
{
clockIn = DateTime.Now;
}
public void outButton_Click(object sender, EventArgs e)
{
DateTime clockOut = DateTime.Now;
TimeSpan timeWorked = clockOut - clockIn;
string timeWorkedReport = $"Time worked = {timeWorked.Hours} hours, {timeWorked.Minutes} minutes";
timeLabel.Text = timeWorkedReport;
}
}
问题:创建一个由打卡按钮、打卡按钮和标签组成的程序来保存总工作时间。
这段代码看起来应该很简单,但我知道我遗漏了一些东西。我无法从 inButton 单击获取 DateTime clockIn 以在 outButton 单击中与 TimeSpan 一起使用。我是 C# 的新手,所以欢迎任何批评。谢谢!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TimeClock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void inButton_Click(object sender, EventArgs e)
{
DateTime clockIn = DateTime.Now;
}
public void outButton_Click(object sender, EventArgs e)
{
DateTime clockOut = DateTime.Now;
TimeSpan timeWorked = clockOut - clockIn;
string timeWorkedReport = $"Time worked = {timeWorked.Hours} hours, {timeWorked.Minutes} minutes";
timeLabel.Text = timeWorkedReport;
}
}
}
最重要的是,您需要阅读有关变量范围和数据成员的内容。
不太重要 - 以下将起作用:
我刚刚将您的变量提升为 Class 数据成员。
public partial class Form1 : Form
{
DateTime clockIn = DateTime.Min; // Move Here
public Form1()
{
InitializeComponent();
}
public void inButton_Click(object sender, EventArgs e)
{
clockIn = DateTime.Now;
}
public void outButton_Click(object sender, EventArgs e)
{
DateTime clockOut = DateTime.Now;
TimeSpan timeWorked = clockOut - clockIn;
string timeWorkedReport = $"Time worked = {timeWorked.Hours} hours, {timeWorked.Minutes} minutes";
timeLabel.Text = timeWorkedReport;
}
}