One way to use a singleton as a global variable

Source: Internet
Author: User

Content of this article: a simple way to use a single instance as a global variable. Use the Code to make it clearer.

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 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.