C# ?? 操作符示例

static int? GetNullableInt()
{
    return null;
}

static string GetStringValue()
{
    return null;
} 

static void Main(string[] args)
{
    // ?? 操作符 示例
    int? x = null;

    // y = x, x 如果等于 null,y=-1
    int y = x ?? -1;
    Console.WriteLine(y);

    //如果 GetNullableInt方法返回 null,i 等于 defalut(int) ,defalut(int) 等于 0
    int i = GetNullableInt() ?? default(int);
    Console.WriteLine(i);

    string s = GetStringValue();
    //如果 s 为空的话把 s 赋值为 Unspecified
    Console.WriteLine(s ?? "Unspecified");            
}

 

posted @ 2013-08-04 17:38  罗马景行  阅读(154)  评论(0编辑  收藏  举报