C# 条件变量

C# 条件变量,c#,asp.net,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(); 基本上,当页面加载

我错过了一些东西,我该怎么做

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为空,则用我预定义的内容填充日期。

您忘记了一个
及其后的部分

条件运算符有三个部分:

  • 谓词(
    Request.QueryString[“sd”]==String.Empty
  • 真枝
  • 假枝
您缺少错误的分支语法和值

我会这样写:

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

string.IsNullOrWhitespace
是.NET 4.0的新版本,因此在早期版本中使用
string.IsNullOrEmpty

它应该类似于:

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

条件运算符的语法为:

condition ? truevalue : falsevalue
当条件为false时,缺少冒号和的值

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

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();

是的;如果未提交任何值,则
Request.QueryString[]
将返回
null
(而不是
String.Empty
)。@p.campbell-确实。。。虽然如果需要字符串,则不需要往返。错过了,谢谢你!我想知道我错过了什么。感谢您对我的详细解释。:)我是否缺少顶部的using语句?它是说“字符串”不包含“IsNullOrWhitespace”的定义@JamesWilson-我添加了一个关于这个的注释。。。这是一个.NET4.0的添加。如果尚未在4.0上运行,请使用
string.IsNullOrEmpty