2011-01-31 78 views
6

thể trùng lặp:
What is the “??” operator for?gì dấu hỏi đôi có nghĩa là trong C#

Gỡ rối một số mã và tìm thấy ?? bên trong mã. Điều đó có nghĩa là gì?

+6

Câu hỏi này được hỏi nhiều hơn mười lần trong chính ngăn xếp chồng. Một số người trong số họ đang ở đây. 1. http://stackoverflow.com/questions/827454/what-is-the-operator-for 2. http://stackoverflow.com/questions/3925726/coalesce-operator-in-c 3. http: // stackoverflow.com/questions/770096/what-does-mean. – Bipul

Trả lời

16

??null-coalescing operator cho các loại có thể vô hiệu.

object obj = canBeNull ?? alternative; 

// equivalent to: 
object obj = canBeNull != null ? canBeNull : alternative; 
+1

+1 Từ tôi - chỉ để nitpick, nó thực sự được gọi là * null-coalescing operator *. (http://msdn.microsoft.com/en-us/library/ms173224.aspx). Nó rất hữu ích ngay cả khi bạn không gán các giá trị cho một biến. –

+1

bạn có nghĩa là "toán tử kết hợp không" phải không? –

+0

ahem! Tôi đã làm. đỏ mặt ... Thx guys. –

5

http://msdn.microsoft.com/en-us/library/ms173224.aspx tham chiếu điều này để mô tả. đó là một toán tử

Toán tử ?? xác định giá trị mặc định được trả lại khi loại có thể gán được gán cho loại không thể vô hiệu.

// ?? operator example. 
    int x = null; 

    // y = x, unless x is null, in which case y = -1. 
    int y = x ?? -1; 

    // Assign i to return value of method, unless 
    // return value is null, in which case assign 
    // default value of int to i. 
    int i = GetNullableInt() ?? default(int); 

    string s = GetStringValue(); 
    // ?? also works with reference types. 
    // Display contents of s, unless s is null, 
    // in which case display "Unspecified". 
    Console.WriteLine(s ?? "Unspecified"); 
Các vấn đề liên quan