?: ?? Operators Instead Of IF|ELSE

前端 未结 9 1611
粉色の甜心
粉色の甜心 2020-11-28 02:09
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
                


        
相关标签:
9条回答
  • 2020-11-28 02:35

    If you are concerned with the verbosity of your code I would write this rather than trying to abuse expressions.

    if (Source == value) return;
    Source = value;
    RaisePropertyChanged("Source");
    
    0 讨论(0)
  • 2020-11-28 02:35

    I don't think you can its an operator and its suppose to return one or the other. It's not if else statement replacement although it can be use for that on certain case.

    0 讨论(0)
  • 2020-11-28 02:39

    For [1], you can't: these operators are made to return a value, not perform operations.

    The expression

    a ? b : c
    

    evaluates to b if a is true and evaluates to c if a is false.

    The expression

    b ?? c
    

    evaluates to b if b is not null and evaluates to c if b is null.

    If you write

    return a ? b : c;
    

    or

    return b ?? c;
    

    they will always return something.

    For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.

    0 讨论(0)
  • 2020-11-28 02:39

    The "do nothing" doesn't really work for ?

    if by // Return Nothing you actually mean return null then write

    return Source;
    

    if you mean, ignore the codepath then write

     if ( Source != null )
                {
                    return Source;
                }
    // source is null so continue on.
    

    And for the last

     if ( Source != value )
                { Source = value;
                    RaisePropertyChanged ( "Source" );
                }
    
    // nothing done.
    
    0 讨论(0)
  • 2020-11-28 02:50

    The ?: Operator returns one of two values depending on the value of a Boolean expression.

    Condition-Expression ? Expression1 : Expression2
    

    Find here more on ?: operator, also know as a Ternary Operator:

    • http://net-informations.com/csprj/statements/cs-operator.htm
    0 讨论(0)
  • 2020-11-28 02:53

    the ?: is the itinerary operator. (believe i spelled that properly) and it's simple to use. as in a boolean predicate ? iftrue : ifalse; But you must have a rvalue/lvalue as in rvalue = predicate ? iftrue: iffalse;

    ex int i = x < 7 ? x : 7;

    if x was less than 7, i would get assigned x, if not i would be 7.

    you can also use it in a return, as in return x < 7 ? x : 7;

    again, as above , this would have the same affect.

    so, Source = Source == value ? Source : string.Empty; i believe is what your trying to acheive.

    0 讨论(0)
提交回复
热议问题