繁体   English   中英

带有“?”和“ ??”的代码是什么意思?

[英]What does this code with “?” and “??” mean?

这个语法是什么意思? 当我看这段代码时,我目前正在编写c#4.0。

_data = (SerializationHelper.Deserialize(Request.Form[_dataKey])
             ? TempData[_dataKey] ?? new ProfileData ()) as ProfileData;

如果我要在IF语句中编写它,那会是什么?

编译器给我一个错误的提示,原因是它不写:以及需要更多东西吗?

?? 表示如果为空,则使用其他值。 例如

var name = somevalue ?? "Default Name";

如果somevalue为null,它将分配值“默认名称”

还单? 是三元运算符,基本上可以这样使用它:

var example = (conditional statement here) ? value_if_true : value_if_false;

但是,当我正确看待您的代码时,似乎没有遵循适用于三元运算符的正确语法,就像Corey所说的那样,您可能错过了?吗? 关??。

看起来您错过了? 那里。 我怀疑它应该读为:

_data = (SerializationHelper.Deserialize(Request.Form[_dataKey])
            ?? TempData[_dataKey]
            ?? new ProfileData()
        ) as ProfileData;

在C#中,操作A ?? B A ?? B直接等于(A == null ? B : A) ,或者if (A == null) return B; return A; if (A == null) return B; return A; 如果你更喜欢。

因此,您的上述声明等同于:

object tmp = SerializationHelper.Deserialize(Request.Form[_dataKey]);
if (tmp == null)
{
    tmp = TempData[_dataKey];
    if (tmp == null)
        _tmp = new ProfileData();
}
_data = tmp as ProfileData;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM