我不是在谈论javascript,但在javascript中,我可以声明string
这样:
var identity = {
getUserId: function () {
return 'userid';
}
};
var userid = identity.getUserId() || '';
这意味着:如果identity.getUserId()
为空或未定义,则值''
将自动投放到userid
。
现在,在C#中:
public static void AddOnlineUser(this IIdentity identity)
{
string userid = identity.GetUserId();
// long way to check userid is null or not:
if (string.IsNullOrEmpty(userid))
{
userid = "";
}
// invalid C# syntax:
// Operator || cannot be applied to operands of type 'string' and 'string'
// string userid = idenity.GetUserId() || "";
// Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// string.IsNullOrEmpty(userid) ? "" : userid;
}
我不是说:want to create a C# variable same as javascript syntax
。但在这种情况下,如果它在一行中为null或为空,有没有办法将值""
转换为userid
?
答案 0 :(得分:6)
Null Coalescing Operator <{1}}
C#拥有自己的null-coalescing operator ??
来处理空值:
??
请注意,如果语句中的第一个值为// This will use the available GetUserId() value if available, otherwise the empty string
var userid = identity.GetUserId() ?? "";
,则此运算符仅按预期工作,否则将使用该值。如果有可能不是这种情况(并且您可能遇到非空的无效值),那么您应该考虑使用三元运算符。
三元运算符null
否则,您可以使用ternary operator ?:
(即内联if语句)来执行此检查。这与您提供的示例类似,但值得注意的是您需要将?:
实际设置为结果:
userid