[C#]??運算子

  • 6504
  • 0
  • C#
  • 2012-11-02

[C#]??運算子

//原式
//if (i == null)
//{
//    j = 100;
//}
//Console.WriteLine(j);

可簡化為
int j = i ?? 100;//如果i的HasValue為true,則j=i,否則j=100

 

我在做這個範例的時候,因為 int? i=null;

一直少打了 ? 號,所以一直出現錯誤,所以?? 應該是要和 ? 搭配使用吧

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //int i = null;
            int? i=null;
            int j = i ?? 100;//如果i的HasValue為true,則j=i,否則j=100
            Console.WriteLine(j);
            i = 99;
            j = i ?? 100;
            Console.WriteLine(j);
            Console.Read(); 
        } 
    }
}

 


如有錯誤 歡迎指正