更新时间:2023-02-06 16:52:24
学习编写可读代码。至少有4件事让你的代码难以理解:
#1你不使用缩进
#2你不要在一些额外的空行添加适当的位置。
#3你声明你从不使用的变量
#4你有很多变量可以复制其他变量。
另外:
*您必须使用TryParse
处理错误的用户输入并采取适当的措施输入错误时的动作。
*在实际应用中,你必须考虑到用户可能想要以24小时格式输入时间这一事实。
*您可能无法正确处理在12:00 AM到12:59 AM之间结束的额外时间,因为系统地添加了12个小时。
*每个案例的代码都类似,所以你应该有处理的函数常用代码。
*如果所有其他情况似乎成对使用,那么额外的使用目的尚不清楚...但是对于额外的系统而言加上12个小时。
*你的输出格式可能不是预期的。您可能想要使用@hh \:mm
。
*TimeSpan(0)
没用,因为已有一个属性:TimeSpan.Zero
。如果使代码更有效,更可读。
从你的问题是不清楚什么是所需的输出格式。看来你想要输出一个时间跨度,所以军事与标准时间似乎不适合你的代码!
这里是重构的代码,基本上是相同的作为你的东西(除了我测试不良输入):
Learn to write readable code. There are at least 4 things that make your code hard to read:
#1 You don't use indentation
#2 You don't add some extra blank lines at appropriate locations.
#3 You declare variable you never use
#4 You have many variable that duplicate other variables.
Also:
* You have to handle wrong user inputs by usingTryParse
and take the appropriate action when the input is bad.
* In real application, you have to take into account the fact that user might want to enter time in 24 hours format too.
* You probably does not correctly handle extra time that ends between 12:00AM and 12:59AM inclusively as you systematically add 12 hours.
* The code for each case would be similar so you should have functions that handle common code.
* How extra is intended to be use is not clear as all other cases appears to work in pairs... but for extra you systematically add 12 hours.
* Your output format is probably not the expected one. You probably want to use@"hh\:mm"
instead.
*TimeSpan(0)
is useless as there is already a property for that:TimeSpan.Zero
. If make the code more efficient and more readable.
From your question is is not clear what is the desired output format. It seems that you want to output a time span so the military vs standard time does not seems to fit your code!
Here is the refactored code that does essentially the same things as your (except that I test for bad inputs):
DateTime amtimein, amtimeout;
if (!DateTime.TryParse(txt1.Text + "AM", out amtimein))
{
// Warn user that hour # 1 is not valid...
}
else if (!DateTime.TryParse(txt2.Text + "AM", out amtimeout))
{
// Warn user that hour # 2 is not valid...
}
else
{
TimeSpan diff = amtimeout.Subtract(amtimein);
if (diff < TimeSpan.Zero)
{
diff += TimeSpan.FromHours(12);
}
var txtm.Text = diff.ToString(@"hh\:mm");
}