条件变量

时间:2012-05-03 15:26:37

标签: c# asp.net

我遗失了一些东西,我该怎么做呢?

var now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths( -14 ).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ] == String.Empty ? now.ToShortDateString();

基本上,如果sd和/或ed是空白页面,那么用我预先定义的东西填充日期。

3 个答案:

答案 0 :(得分:5)

您忘记了:及其之后的部分。

条件运算符有三个部分:

  • 谓词(Request.QueryString["sd"] == String.Empty
  • true branch
  • false branch

您缺少false分支语法和值。

我会把它写成:

string loadStartDate = string.IsNullOrWhitespace(Request.QueryString["sd"])
                       ? now.AddMonths( -14 ).ToShortDateString()
                       : Request.QueryString["sd"];

注意:

string.IsNullOrWhitespace是.NET 4.0的新手,因此请使用string.IsNullOrEmpty作为先前版本。

答案 1 :(得分:1)

应该是这样的:

string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths
( -14 ).ToShortDateString():SOME OTHER VALUE;

答案 2 :(得分:1)

条件运算符的语法是:

condition ? truevalue : falsevalue

您缺少冒号以及条件为假时的值。

可以使用条件运算符,但它会有一点重复。就这样做:

DateTime now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"];
if (String.IsNullOrEmpty(loadStartDate)) loadStartDate = now.AddMonths(-14).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ];
if (String.IsNullOrEmpty(loadEndDate)) loadEndDate = now.ToShortDateString();