单例作为全局变量的一种方式

本文内容:利用单例的方式实现一个作为全局变量的简单方法。用代码说明,比较清晰一点。

UserPool.cs

View Code
 1 class UserPool
2 {
3 publicstaticreadonly UserPool GlobalUserPool =new UserPool();
4 private Hashtable ht =new Hashtable();
5
6 private UserPool()
7 {
8 }
9 publicvoid Add(string key, UserInformation userInfor)
10 {
11 lock (ht.SyncRoot)
12 {
13 ht[key] = userInfor;
14 }
15 }
16
17 publicvoid Remove(string key)
18 {
19 if (ht.ContainsKey(key))
20 {
21 lock (ht.SyncRoot)
22 {
23 if (ht.ContainsKey(key))
24 {
25 ht.Remove(key);
26 }
27 }
28 }
29 }
30
31 public UserInformation GetUserInfo(string key)
32 {
33 if (ht.ContainsKey(key))
34 {
35 lock (ht.SyncRoot)
36 {
37 if (ht.ContainsKey(key))
38 {
39 return ht[key] as UserInformation;
40 }
41 else
42 {
43 returnnull;
44 }
45 }
46 }
47 else
48 {
49 returnnull;
50 }
51 }
52
53 publicbool ContainsKey(string key)
54 {
55 return ht.ContainsKey(key);
56 }
57 }

UserInformation.cs

View Code
1 class UserInformation
2 {
3 publicstring[] UserFriends { get; set; }
4 publicstring KeyGuid { get; set; }
5 publicstring Name { get; set; }
6 }

转载于:https://www.cnblogs.com/xyz168/archive/2011/08/19/2145321.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值