双重问号在c#中意味着什么

时间:2011-01-31 06:16:41

标签: c# .net

  

可能重复:
  What is the “??” operator for?

调试一些代码并找到?​​?在代码里面。这是什么意思?

2 个答案:

答案 0 :(得分:16)

??是可以为空的类型的null-coalescing operator

object obj = canBeNull ?? alternative;

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

答案 1 :(得分:5)

http://msdn.microsoft.com/en-us/library/ms173224.aspx请参阅此说明。这是一个运营商

??运算符定义了将可空类型分配给非可空类型时要返回的默认值。

    // ?? 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");