1. 程式人生 > >C# 可空型別 匿名方法 迭代器

C# 可空型別 匿名方法 迭代器

可空型別Demo

using System;

namespace NullDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //?語法糖
            DateTime? date= null;
            int? a = null;

            //獲取預設值
            DateTime c = date.GetValueOrDefault();
            int d = a.GetValueOrDefault();

            //空合併操作符號??左邊為null時取右邊
            DateTime dateNew = date ?? DateTime.Now;
            int b = a ?? 123;

            Console.WriteLine(dateNew);
            Console.WriteLine(b);
            Console.WriteLine("default DateTime"+c);//0001/1/1 0:00:00
            Console.WriteLine("default int" + d);//0

            Console.WriteLine("----------------------------");


            date = DateTime.Now.AddDays(1);
            a = 1;
            //空合併操作符號??左邊不為null時取左邊
            dateNew = date ?? DateTime.Now;
            b = a ?? 123;

            Console.WriteLine(dateNew);
            Console.WriteLine(b);

            Console.Read();
        }
    }
}

 匿名方法Demo

using System;

namespace AnonymousDemo
{
    class Program
    {
       

        delegate void ClosureDelegate();

        private static ClosureDelegate CreateDelegateInstance()
        {
            int count = 1;//外部變數
            //匿名方法
            ClosureDelegate closureDelegate = delegate
            {
                Console.WriteLine(count);
                count++;
            };
            //呼叫委託
            closureDelegate();//此時輸出1
            return closureDelegate;
        }

        static void Main(string[] args)
        {
            ClosureDelegate test = CreateDelegateInstance();//此時輸出1
            test();//執行匿名方法,外部變數count是引用地址,相當於全域性變數,輸出2
            Console.Read();
        }
    }
}