如何在性能和可读性方面优化此代码?

时间:2015-09-04 10:16:38

标签: c# asp.net datetime

我想要的输出:

如果差异小于一分钟,结果应为"刚刚更新"如果差异大于一分钟且不到一小时,那么结果应为"更新X分钟前"

代码:

string result = "";
if (difference.Days == 0)
{
    if (difference.Hours == 0)
    {
        if (difference.Minutes == 0)
        {
            result = "Updated just now";
        }
        else
        {
            result = "Updated " + difference.Minutes.ToString() + " minutes ago";
        }                   
    }
    else
    {
        result = "Updated " + difference.Hours.ToString() + " hours ago";
    }
}
else
{
    result = "Updated " + difference.Days.ToString() + " days ago";
}

2 个答案:

答案 0 :(得分:2)

string result = "Updated ";

if (difference.Days != 0)
    result += difference.Days.ToString() + " days ago";
else if (difference.Hours != 0)
    result += difference.Hours.ToString() + " hours ago";
else if (difference.Minutes != 0)
    result += difference.Minutes.ToString() + " minutes ago";
else
    result += "just now";

答案 1 :(得分:2)

string format = "Updated {0} {1} ago";
string result = "Updated just now";
// this test can be deleted
if(difference.TotalSeconds > 60)
{
  if(difference.Days != 0)
    result = string.Format(format, difference.Days, "days");
  else if (difference.Hours != 0)
    result = string.Format(format, difference.Hours, "Hours");
  else if (difference.Minutes != 0)
    result = string.Format(format, difference.Minutes, "Minutes");
}

以便结果更清洁,更换"天"按difference.Days > 1 ? "Days" : "Day"

格式字符串的目的是避免内存泄漏并允许用户轻松更改文本格式以及用于multilang