当前上下文错误中是否存在if/else变量声明和对象 [英] if/else variable declaration and object does not exist in current context error
问题描述
我有以下代码声明两个变量,然后执行查询.无论如何都将创建变量,所以令我惊讶的是,当要执行查询时,当前上下文错误中没有对象不存在
.我该怎么做?它已经发生过好几次了.我也尝试在变量的声明中使用if/else语句,但这没有用.(然后我得到错误的无效表达式,如果
)我需要说些什么才能使它起作用?
I have the following code which declares two variables and then executes a query. The variables will be created no matter what, so I am surprised to be getting an object does not exist in current context error
when the query is about to execute. How can I do something like this? It has happened several times. I also tries to use an if/else statement in the declaration of the variable but that has not worked. (Then I get the error invalid expression if
) What do I need to say for this to work?
if (from_date == null) {
var from_date_choose = DateTime.Today.AddDays(-30);
} else {
var from_date_choose = from_date;
}
if (to_date == null) {
var to_date_choose = DateTime.Today;
} else {
var to_date_choose = to_date;
}
var voyages = db.Voyages
.Where(v => v.ArrivalDatetime >= from_date_choose)
.Where(v => v.ArrivalDatetime <= to_date_choose);
推荐答案
像这样修改代码,否则您的变量仅存在于本地范围内.您还需要使用 from_date.Value
和 to_date.Value
(我假设它们的类型为 Nullable< DateTime>
):
Modify the code like this, otherwise your variables exist only in local scope. You also need to use from_date.Value
and to_date.Value
(I assume these are of type Nullable<DateTime>
):
DateTime from_date_choose;
if (from_date == null) {
from_date_choose = DateTime.Today.AddDays(-30);
} else {
from_date_choose = from_date.Value;
}
DateTime to_date_choose;
if (to_date == null) {
to_date_choose = DateTime.Today;
} else {
to_date_choose = to_date.Value;
}
var voyages = db.Voyages
.Where(v => v.ArrivalDatetime >= from_date_choose)
.Where(v => v.ArrivalDatetime <= to_date_choose);
您也可以使用三元运算符,例如:
You may also use the ternary operator, eg.:
DateTime from_date_choose = from_date == null ? DateTime.Today.AddDays(-30) : from_date.Value;
或者正如Jeppe Stig Nielsen建议使用合并运算符,例如:
Or as Jeppe Stig Nielsen suggested use coalesce operator, eg:
DateTime from_date_choose = from_date ?? DateTime.Today.AddDays(-30);
这篇关于当前上下文错误中是否存在if/else变量声明和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!