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;
}
}
}
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;
}
}
}
相关文章推荐
- C#桌面办公应用-工资管理系统系列九
- [c#基础]AutoResetEvent
- C# 6.0那些事
- [C#]冒泡排序
- C#里的Math方法
- c#生成XML文件
- C#如何一个方法实现多个返回值(out和ref的区别)
- C#获得枚举类型的长度
- WPF 与 WinForm 调用系统右键菜单/资源管理器右键菜单/桌面右键菜单
- C#特性的分类
- Linq联合查询
- [C#]变量初始化问题:字段初始值无法引用非静态字段、方法或属性
- Razor语法与布局
- c# int与string的转换
- WinForm+C#代码实现控制应用程序自启动功能
- vs2010 solidworks2015 c# add-in模板 二次开发
- 线性表
- C#反射
- 一次爬虫实践学习(C#)
- Winform跨程序发送、接收消息