1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
5
namespace ConsoleApplication1
6
{
7
class Program
8
{
9
static void Main(string[] args)
10
{
11
Test t = Test.Instance();
12
Console.WriteLine(t.ToString());
13
Test c = Test.Instance();
14
Console.WriteLine(c.ToString());
15
Console.ReadLine();
16
}
17
}
18
19
public class Test
20
{
21
public static int x = 1;
22
private static Test m_Instance;
23
24
private Test()
25
{
26
x++;
27
}
28
29
public static Test Instance()
30
{
31
if (m_Instance == null)
32
{
33
m_Instance = new Test();
34
}
35
else
36
{
37
return m_Instance;
38
}
39
}
40
41
public override string ToString()
42
{
43
return x.ToString();
44
45
}
46
}
47
}
48

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

这是单件模式的基本代码,在这里重载了tostring()方法来查看TEST到底被实例化了多少次,在看了MSDN中关于??运算符的帮助后试着用如下方法来重写INSTANCE方法
public static Test Instance()
{
m_Instance = m_Instance ?? new Test();
return m_Instance;
}
同样可以达到单件模式的功能
MSDN中关于??操作符的定义
如果 ?? 运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数。
可空类型可以包含值,或者可以是未定义的。?? 运算符定义当可空类型分配给非可空类型时返回的默认值。如果在将可空类型分配给非可空类型时不使用 ?? 运算符,将生成编译时错误。如果使用强制转换,并且当前未定义可空类型,将发生 InvalidOperationException 异常。