简体   繁体   English

C#相当于JavaScript“ OR分配”

[英]C# equivalent to JavaScript “OR assignment”

Does C# have an equivalent to JavaScript's assignment syntax var x = y || z; C#是否等效于JavaScript的赋值语法var x = y || z; var x = y || z; ? In case you don't know, the result is not true/false . 如果您不知道,结果将不是true/false If y is defined, then it is assigned to x , otherwise z is assigned to x even if it is undefined. 如果定义了y ,则将其分配给x ,否则将z分配给x即使未定义也是如此。

Note that in JavaScript the variable still has to be declared: var test; 请注意,在JavaScript中,仍必须声明变量: var test;

I think that you are looking for ?? 我认为您正在寻找?? operator. 操作员。

MSDN Reference MSDN参考

var abc = blah ?? "default";

是的

这就是你要找的

var x = y ?? z;

In C# there's no such notion as variable not being defined. 在C#中,没有这样的概念,即未定义变量。 Such operator doesn't make sense in C#. 这样的运算符在C#中没有意义。

Unlike JavaScript, C# is not dynamic but static language so that such operation is impossible - a compilation error will occur. 与JavaScript不同,C#不是动态语言而是静态语言,因此无法进行此类操作-会发生编译错误。

Imagine you're writing this if : 想象一下, if您正在编写此代码, if

if(pizzaPrice == hamburgerPrice)

Before declaring the variables first: 在首先声明变量之前:

decimal pizzaPrice;
decimal hamburgerPrice;

An error will occur on compile-time. 编译时将发生错误。

Update: Even if the variables were declared it doesn't matter because C# does not support such a feature. 更新:即使声明了变量,也没关系,因为C#不支持这种功能。

On the other hand, JavaScript is enforcing evaluation of the variable in if conditions by calling the ToBoolean method and if it's undefined or null it's equals to false and C# doesn't not contains such a behavior. 另一方面,JavaScript通过调用ToBoolean方法在条件if情况下强制执行变量的评估,如果undefined或为null则它等于 false并且C#不包含这种行为。

Look at this cool article: JavaScript pitfalls: null, false, undefined, NaN 看看这篇很酷的文章: JavaScript陷阱:null,false,undefined,NaN

But if you want to check if a variable is referencing to a null you can easily use the null coalescing operator "??" 但是,如果要检查变量是否引用了null ,则可以轻松使用null合并运算符 “ ??”。 operator. 操作员。

As the following: 如下:

var x = y ?? z;

Yes, there is: ?? 是的,有: ??

string x = y ?? z;

Which basically calculates: 基本上是这样计算的:

string x = y != null ? y : z

However, there are a few differences between Javascript and C#. 但是,Javascript和C#之间有一些区别。 As with JS, y and z must both be declared before hand. 与JS一样, yz必须事先声明。 However, unlike JS, y and z must also be "assigned" in C# or a compiler error will be thrown as usual. 但是,与JS不同, yz也必须在C#中“分配”,否则将照常引发编译器错误。

The operator requires a nullable type and it checks whether the first is null before returning the second. 运算符需要可为null的类型,并在返回第二个值之前检查第一个是否为null。 You can chain a whole bunch ( a ?? b ?? c ?? d ?? e ) if you want. 如果需要,可以将一整串( a ?? b ?? c ?? d ?? e )链在一起。

Note that a zero length string is not null. 请注意,零长度的字符串不为 null。

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

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