gpt4 book ai didi

c# - 是否有更有效的方法来编写使用 DateTime 值的 IF 语句?

转载 作者:行者123 更新时间:2023-11-30 19:37:50 25 4
gpt4 key购买 nike

我有一大堆 if 语句,将当前日期与设定的截止日期进行比较,然后显示距离截止日期还有多少天,或者显示是否已经达到截止日期。只是想知道是否有更有效的方法来解决这个问题。

下面是其中一组语句的示例,还有大约 7 个这样的语句。这几乎有点恶心,在我如何整理它的正确方向上寻找一点帮助或一点。谢谢!

if (DateTime.Now >= programming1)
{
lblReadDate.Text = "Due date for Programming Assignment 1 has been reached (" + programming1.ToShortDateString() + ").";
}
else
{
lblReadDate.Text = "Days remaining until Programming Assignment 1 deadline: " + daysRemaining1.ToString("0");
}

if (DateTime.Now >= programming2)
{
lblReadDate2.Text = "Due date for Programming Assignment 2 has been reached (" + programming2.ToShortDateString() + ").";
}
else
{
lblReadDate2.Text = "Days remaining until Programming Assignment 2 deadline: " + daysRemaining2.ToString("0");
}

最佳答案

很难说哪种方法最适合您,但我假设您通常希望有一个代表作业的类,例如:

public class Assignment
{
public string Name { get; set; }
public DateTime DueDate { get; set; }

// This is just one of many ways to do it.
// This can be an extension method, for example.
// Note also that DateTime.UtcNow is changing as
// you are traversing the list.
public bool IsOverdue
{
get { return DateTime.UtcNow > DueDate; }
}
}

关联两个实体(在本例中为分配实例和标签)的一般方法是通过 Dictionary<TKey, TValue> .在这种情况下,您可以按分配名称进行映射,以保持简单:

// This is just one of many ways to do it.
// You could make Assignment implement IEquatable, or
// specify a custom comparer and map from actual
// Assignment to a Label, for instance.
var assignmentToLabelMap = new Dictionary<string, Label>
{
{ "Programming Assignment 1", label1 },
{ "Programming Assignment 2", label2 },
{ "Programming Assignment 3", label3 }
}

一旦准备就绪,您的 UI 更新就很简单了:

// Get the assignments
IList<Assignment> assignments = GetTheListOfAssignments();

// Update labels
foreach (var assignment in assignments)
{
// no error checking here whatsoever
var label = assignmentToLabelMap[assignment.Name];

if (assignment.IsOverdue)
label.Text = xxx;
else
label.Text = yyy;
}

因为您似乎在使用 WinForms,您可能还想实现 INotifyPropertyChanged并配置控件绑定(bind)以使所有这一切自动发生,但仍然需要在某个时间遍历列表以触发更改。

关于c# - 是否有更有效的方法来编写使用 DateTime 值的 IF 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36695239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com