问题描述:

Does C# have something like the JavaScript if or value syntax?

For example, I know you can do this in JavaScript:

var test = someValue || thisValue;

if someValue is undefined, false, or empty string, then test becomes thisValue. However, I've never seen a way to do this in C# other than a traditional if, or inline if.

网友答案:

NullCoalesce

var test = someValue ?? thisValue;

However, C# doesn't do weird JavaScript falsey behaviors.

The short circuit evaluation in C# is more pertinent in evaulating bools:

private bool EvaluateA()
{
    return true;
}

private bool EvaluateB()
{
    return false;
}

public static int main()
{
    Console.Write(EvaluateA() || EvaluateB()); // EvaluateB is never called
}
网友答案:

Its called the null-coalescing operator.

String someValue = null;
var thisValue = "Foo";
var test = someValue ?? thisValue;
// test will be == "Foo"

As mentioned in the comments, this doesn't work for empty strings, "false", etc. What you can do in C# is write an extension method to do that, if you really want to:

public static class MyStringThing {
    public static String FixErUp(this String s1, String s2) {
        if (String.IsNullOrWhiteSpace(s1) || s1.Equals("false"))
            return s2;
        return s1;
    }
}

to be used like so:

String someValue = "false";
var thisValue = "Foo";
var test = someValue.FixErUp(thisValue);
// test will be == "Foo"
网友答案:

Use ??

var test = someValue ?? thisValue;

This only works if someValue is null. To check for false or string.Empty, you'll need to use a normal if statement.

网友答案:

Not really. But it does have null coalescing.

Given a reference type, you could have the value or an alternative if it is null.

string foo = null;
string value = foo ?? "bar"; // value == "bar"

Otherwise for any other case (i.e., non-null, all whitespace, value type, etc.), you'll have to do other forms of checking.

string foo = "";
string value1 = foo ?? "bar"; // value1 == ""
string value2 = !String.IsNullOrEmpty(foo) ? foo : "bar"; // value1 == "bar"
相关阅读:
Top