2012-05-03 22 views
0

何かが欠落していますが、どうすればこの問題を解決できますか?条件変数

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

基本的にはときに、ページのloades SDおよび/またはEDが空白の場合は、その後、私の事前定義されたもので、日付を記入してください。

答えて

5

:とそれ以降の部分を忘れています。

  • 述語(Request.QueryString["sd"] == String.Empty
  • 真枝
  • 偽枝

あなたが偽の分岐構文と値が欠落しています

条件演算子は、3つの部分があります。

私はそれのように記述します。

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; 
+3

'Request.QueryString []'は、値がまったく入力されなかった場合は 'String.Empty'ではなく' null'を返します。 –

+0

@ p.campbell - 確かに...文字列が必要な場合は、往復する必要はありません。それを逃した。 – Oded

+0

ありがとう!私が何が欠けていたのか不思議でした。説明をありがとうございます。 :) –

1

は、それはする必要があります。

You は条件付き演算子を使用しますが、少し繰り返します。次のようにしてください:

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

:あなたはコロンとconditonが偽のときの値が不足している

condition ? truevalue : falsevalue 

よう