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

时间:2016-04-18 13:21:32

标签: c# if-statement

我有一个很大的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");
}

6 个答案:

答案 0 :(得分:4)

很难说哪种方法最适合你,但我认为你通常会想要一个代表作业的类,例如:

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并配置控制绑定以使所有这些自动发生,但仍需要在某个时间迭代列表以触发更改。

答案 1 :(得分:2)

每当你重复代码时,你应该寻找一种概括它的方法,这通常意味着将代码移动到方法甚至新类中。这样的事情现在可以奏效。我没有使用循环,因为我看到你根据你正在检查的值将文本分配给标签。

lblReadDate.Text = compareDate(programming1, "Programming Assignment 1");
lblReadDate2.Text = compareDate(programming2, "Programming Assignment 2");

// common method
public string compareDate(DateTime dateToCompare, string name) {
    if (DateTime.Now >= dateToCompare)
        return "Due date for " + name + " has been reached (" + dateToCompare.ToShortDateString() + ").";
    return "Days remaining until " + name + " deadline: " + dateToCompare.ToString("0");
}

你还应该考虑使用string.Format来清理你的字符串连接(在这种情况下它不会对性能做任何事情,只是让它更容易阅读)。

答案 2 :(得分:1)

将progamming1,progamming2,progamming3,...转换为DateTime []怎么样?你可以使用for循环并保留一个计数器,只需使用counter.ToString()作为赋值号。

答案 3 :(得分:1)

您可以使用Ternary Operators直观地整理它吗?

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

那就是说,扩展方法会有所帮助:

public static class Extensions
{
    public static bool CompareDateToNow(this DateTime compareFrom)
    {
        return DateTime.Now >= compareTo;
    }
}

然后它变成:

lblReadDate.Text = programming1.CompareDateToNow() ?
     string.format("Due date for Programming Assignment 1 has been reached ({0})", programming1.ToShortDateString()) :
     string.format(""Days remaining until Programming Assignment 1 deadline: {0}", daysRemaining1.ToString("0"));

您可以进一步理顺语句中的字符串,最后只需将日期和程序名称传递给它自己的方法。

答案 4 :(得分:0)

很容易重构这种代码。

您可以将代码放在扩展方法中,然后调用它。

例如

lblReadDate.Text = programming1.GetAssignmentMessage("1", daysRemaining1);
lblReadDate2.Text = programming2.GetAssignmentMessage("2", daysRemaining2);

扩展方法:

public static string GetAssignmentMessage(this DateTime programming, string assignment, int daysRemaining)
{
if (DateTime.Now >= programming)
{
    return "Due date for Programming Assignment " + assignment + " has been reached (" + programming.ToShortDateString() + ").";
}
else
{
    return "Days remaining until Programming Assignment " + assignment + " deadline: " + daysRemaining.ToString("0");
}
}

答案 5 :(得分:0)

你应该为你的课程安排如下课程。

    public class Program
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public DateTime DueDate { get; set; }  
    }

您可以将程序对象传递给类似于以下的方法以获取所需的消息。

    Public string GetMessage(Program program)
    {

      if(DateTime.Now > Program.DueDate)
        return string.Format("Due date for Programming Assignment {0} has been reached {1}.",Program.Name,Program.DueDate);    
      else
        string.Format("Days remaining until Programming Assignment {0} deadline: {1}",Program.Name,Program.DueDate);

    }

如果需要在程序对象集合中进行检查。根据需要修改GetMessage方法。

我希望这会对你有所帮助。快乐的编码。 :)