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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值