C#靜態類的使用[簡單]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;




/*靜態變量使用*/
/*以前在C++的博客中也有介紹:靜態變量確實幫助了我們很多,使得程序運用確實比較輕鬆*/
/*實際作用:
 * 對於公有部分,我們可以使用靜態數據,創建一個實例,而使得所有人都能用(有點類似於單例模式)
 * 可以說,如果沒有靜態變量就沒有單例模式這種設計模式
 * 
 * 注意點:與其他變量不同的是,靜態變量在程序運行的時候,只會初始化一次,下次還是直接使用上次的值
 *         (想到了這裏,突然想到斐波那契數列 可以用更簡潔的方法做)
 *         
 *         類內靜態變量只能使用類.靜態變量這種操作方式,但是這種數據依然有privtae,public,protected之分 
 */


namespace StaticClass
{
    class Program
    {
        /* 計算斐波那契數列 */
        static int f = 1;
        static int getF(int i)
        {
            return f = f * i;
        }
        static void Main(string[] args)
        {
            int mul = 1;
            for (int i = 1; i <= 5; i++)
            {
                mul = getF(i);
            }


           // Console.WriteLine("{0}", mul);


            Star[] starYes = ProductStar.Manufacture();
            Console.WriteLine("昨天天空中有{0}顆星星", starYes.Length);


            Star[] starToday = ProductStar.Manufacture();
            Console.WriteLine("今天天空中有{0}顆星星", starToday.Length);


            Star[] starTom = ProductStar.Manufacture();
            Console.WriteLine("明天預測天空中有{0}顆星星", starTom.Length);
        }
    }




    /*類的靜態變量*/
    static class ProductStar
    {
        static Random r = new Random();


        public static Star[] Manufacture()
        {
            Star[] stars = new Star[r.Next(100, 300)];          //創建隨機長度汽車數組
            for (int i = 0; i < stars.Length; i++) stars[i] = new Star();//生產汽車
            return stars;
        }
    }


    class Star
    {
        private int number = 0;


        public Star() { this.number++; }
        public int getNumber(){
            return this.number;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章