简体   繁体   English

C#的操作是否类似于JavaScript的|| 二传手?

[英]Does C# Have An Operation Similar to JavaScript's || Setter?

Does C# have a similar operation to JavaScript's || C#是否与JavaScript的||具有类似的操作 setter? 设定装置?

For example, in JavaScript, if I want to check if a value is null and set a default, I can do something like this: 例如,在JavaScript中,如果我想检查值是否为null并设置默认值,我可以这样做:

function foo(val){
    this.name = val || "foo";
}

But, when I want this functionality in C# I have to go this route: 但是,当我想在C#中使用此功能时,我必须走这条路:

public Foo(string val)
{
    this.name = (string.IsNullOrEmpty(val) ? "foo" : val);
}

I know this is petty and that beggars can't be choosers but, if at all possible, I'd like to avoid getting any answers that involve crazy hacks or extension methods. 我知道这很小,乞丐不能选择,但是,如果可能的话,我想避免得到任何涉及疯狂黑客或扩展方法的答案。 I'm fine with using the ternary operator, but I was just curious if there was a language feature I'd missed. 我使用三元运算符很好,但我很好奇是否有一个我错过的语言功能。

Update: 更新:

Great answers all around, but J0HN and Anton hit it on the head. 各地都有很好的答案,但是J0HN和安东在头上打了一针。 C# doesn't do "falsy" values like JavaScript would in the example above, so the ?? C#没有像上面的例子中的JavaScript那样做“虚假”的值,所以?? operator doesn't account for empty strings. 运算符不考虑空字符串。

Thanks for your time and the great responses! 感谢您的时间和精彩的回复!

There's a null-coalescing operator in C#, though it can't handle all the quirkiness of JavaScript: C#中有一个null-coalescing运算符 ,但它无法处理JavaScript的所有怪癖:

this.name = val ?? "foo";

Since an empty string is false in JavaScript, this C# code will behave differently from its JS counterpart. 由于JavaScript中的空字符串为false ,因此此C#代码的行为与JS对应的代码不同。

You can use ?? 你可以用?? :

private int Foo(string val){
    this.name = val ?? "foo";
}

跟着这个吧

this.name = val ?? "foo";

There is a ?? 有一个?? operator that essentially is the same as COALESCE operator in SQL: 运算符基本上与SQL中的COALESCE运算符相同:

int? a = null; //int? - nullable int
int q = a??1; // q is set to one;

However, ?? 但是, ?? does not check the string for emptiness, so it does not share the same meaning as javascript's || 不检查字符串的空白,因此它与javascript的||没有相同的含义 , which treats empty strings as false as well. ,它也将空字符串视为错误。

Yep, use ??: 是的,使用??:

    private int Foo(string val){
        this.name = val ?? "foo";
    }

Check Msdn for more information: ?? 查看Msdn以获取更多信息: ?? Operator 操作者

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

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