关于.net:双重问号在c#中意味着什么

what does double question marks mean in c#

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
What is the “??” operator for?

调试一些代码并找到??代码内部。这是什么意思?

  • 这个问题在stackoverflow本身中被问了十多次。其中一些在这里。1。stackoverflow.com/questions/827454/what-is-the-operator-for 2.stackoverflow.com/questions/3925726/coalesce-operator-in-c 3.stackoverflow.com/questions/770096/what-does-mean.


??是可为空类型的空合并运算符。

1
2
3
4
object obj = canBeNull ?? alternative;

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

  • +1从我这里——只是为了吹毛求疵,它实际上被称为空合并运算符。(msdn.microsoft.com/en-us/library/ms173224.aspx)。即使不为变量赋值,它也很有用。
  • 你的意思是"空合并运算符",对吗?
  • 啊哼!我做到了。脸红……


http://msdn.microsoft.com/en-us/library/ms173224.aspx有关说明,请参阅此部分。是个接线员

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    // ?? 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");