您的位置:首页 > 编程语言 > C#

C#静态类的使用[简单]

2016-07-17 12:22 267 查看
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;

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: