2012-04-23 3 views
3

아무도 다음 코드를 설명 할 수 있습니까 return total ?? decimal.Zero?C#이 줄은 무엇을 의미합니까?

public decimal GetTotal() 
{ 
    // Part Price * Count of parts sum all totals to get basket total 
    decimal? total = (from basketItems in db.Baskets 
         where basketItems.BasketId == ShoppingBasketId 
         select (int?)basketItems.Qty * basketItems.Part.Price).Sum(); 
    return total ?? decimal.Zero; 
} 

다음과 같은 의미입니까?

if (total !=null) return total; 
    else return 0; 
+0

따라서 약 10 개의 응답을 기반으로 "null-coalescing operator"라고 불립니다. : p – Gravy

답변

13

예, 그것이 의미하는 바입니다. null-coalescing operator이라고합니다.

구문 단축키 일뿐입니다. 그러나 읽는 값은 한 번만 평가되므로 더 효율적일 수 있습니다. (값 회 부작용 평가 여기서 또한 경우에 기능의 차이가있을 수 있음을 참고.)

+2

이 외에도 특정 코드 예제는 10 진수가 0으로 기본 설정되어 있기 때문에 return return.GetValueOrDefault (decimal.Zero) 또는 단순히 return total.GetValueOrDefault()와 동등합니다. – Matthew

1

그것은 최초의 비 - 널 식 반환 (제 식 total 인을, 두 번째 식은 decimal.Zero 임)

따라서 total이 null이면 decimal.Zero이 반환됩니다.

4

null 통합 연산자입니다.

효과적으로, 그것은 코드이 방법을 다시 작성 같다 :

return (total != null) ? total.Value : decimal.Zero; 
+1

아니요, 코드'return (total! = null)을 다시 작성하는 것과 같습니다. total.Value : decimal.Zero;' –

+0

나의 실수는, 나는 그것이 10 진수 였음을 알지 못했다. 나는 대답을 업데이트 할 것이다. – Tejs

2

당신은 그것을 못을 박았다. 이것은 null-coalescing 연산자입니다. 그것을 확인해보십시오 here.

6

C#의 ??null coalescing operator이라고합니다. 그것은 다음 코드

if (total != null) { 
    return total.Value; 
} else { 
    return Decimal.Zero; 
} 

상기 if 문 팽창 사이의 차이점 중 하나와 거의 동등한의 운영자와 ?? 부작용 처리 방법이다. 예에서 값이 total으로되는 부작용은 한 번 발생하지만 if 문에서는 두 번 발생합니다.

total이 로컬이므로 부작용이 없으므로이 경우 중요하지 않습니다. 그러나 속성 또는 메서드 호출을 부작용이라고 말하면 요인이 될 수 있습니다.

// Here SomeOperation happens twice in the non-null case 
if (SomeOperation() != null) { 
    return SomeOperation().Value; 
} else { 
    return Decimal.Zero; 
} 

// vs. this where SomeOperation only happens once 
return SomeOperation() ?? Decimal.Zero; 
+0

더 정확히 말하면, 해당 코드 블록에서 값을 한 번 평가할 수 있습니다. 즉, 'tmp = SomeOperation(); if (tmp! = null) {return tmp.Value; } else {Decimal.Zero를 반환합니다. }' –

관련 문제