C# 类的静态成员

 1 using System;
 2 namespace StaticVarApplication
 3 {
 4     class StaticVar
 5     {
 6        public static int num;
 7         public void count()
 8         {
 9             num++;
10         }
11         public int getNum()
12         {
13             return num;
14         }
15     }
16     class StaticTester
17     {
18         static void Main(string[] args)
19         {
20             StaticVar s1 = new StaticVar();
21             StaticVar s2 = new StaticVar();
22             s1.count();
23             s1.count();
24             s1.count();
25             s2.count();
26             s2.count();
27             s2.count();         
28             Console.WriteLine("s1 的变量 num: {0}", s1.getNum());
29             Console.WriteLine("s2 的变量 num: {0}", s2.getNum());
30             Console.ReadKey();
31         }
32     }
33 }

当上面的代码被编译和执行时,它会产生下列结果:

s1 的变量 num: 6
s2 的变量 num: 6

声明一个类成员为静态时,意味着无论有多少个类的对象被创建,只会有一个该静态成员的副本。

转载于:https://www.cnblogs.com/krystalstar/p/9618004.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值