這是我的代碼:爲什麼我不能完成這項任務?
DateTime? test;
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null));
爲什麼自己不能變量設置爲null
?
這是我的代碼:爲什麼我不能完成這項任務?
DateTime? test;
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null));
爲什麼自己不能變量設置爲null
?
與Nullable<T>
做(在這種情況下,DateTime?
),錯誤是專門在這裏發生的事情:試試這個
((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null))
注意,有沒有一個可爲空DateTime
提這段代碼。在將此代碼的結果分配給可爲空的DateTime
之前,需要對此代碼本身進行評估。它不可能,因爲你看到的錯誤。
正在使用的運算符(: ?
)需要能夠從操作的所有參數中推斷出類型,並且這些類型需要能夠匹配。在這裏你傳遞一個DateTime
和null
這是無法匹配的。嘗試投一個參數:
((objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday : null))
嘗試用
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday): null;
說明:三元操作符的結構是:
variable = (condition)?(value if yes):(value if no);
你需要零轉換爲可空的日期時間:
(DateTime?)null
在這種情況下不能設置爲空,因爲三元運算符必須返回相同類型的值從任何除了
test = (objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday): null;
您在該代碼中有不匹配的圓括號,這使得它很難理解。 –
您收到的錯誤是什麼? – David
這是一個帶有一個參數的三級運算符嗎? – opalenzuela