-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathGotoExercise.cs
136 lines (125 loc) · 3.76 KB
/
GotoExercise.cs
1
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
namespace HelloDotNetGuide.CSharp语法
{
public class GotoExercise
{
/// <summary>
/// 使用goto进行代码重试示例
/// </summary>
public static void GotoRetryUseExample()
{
int retryCount = 0;
for (int i = 0; i < 10; i++)
{
retryLogic:
try
{
//模拟可能出错的操作
Random random = new Random();
int result = random.Next(0, 2);
if (result == 0)
{
throw new Exception("Error occurred");
}
Console.WriteLine("Operation successful on attempt: " + retryCount);
}
catch (Exception ex)
{
retryCount++;
if (retryCount < 3)
{
Console.WriteLine("Error occurred, retrying...");
goto retryLogic; //跳转到重试逻辑
}
else
{
Console.WriteLine("Max retry limit reached.");
return;
}
}
}
}
/// <summary>
/// 不使用goto进行代码重试示例
/// </summary>
public static void NonGotoRetryUseExample()
{
int retryCount = 0;
for (int i = 0; i < 10; i++)
{
while (retryCount < 3)
{
try
{
//模拟可能出错的操作
Random random = new Random();
int result = random.Next(0, 2);
if (result == 0)
{
throw new Exception("Error occurred");
}
Console.WriteLine("Operation successful on attempt: " + retryCount);
break;
}
catch (Exception ex)
{
retryCount++;
Console.WriteLine("Error occurred, retrying...");
}
}
if (retryCount == 3)
{
Console.WriteLine("Max retry limit reached.");
return;
}
}
}
/// <summary>
/// goto正常输出使用示例
/// </summary>
public static void GotoGeneralUseExample(int num)
{
if (num < 0)
{
goto LessThanZero;
}
else if (num == 0)
{
goto EqualToZero;
}
else
{
goto GreaterThanZero;
}
LessThanZero:
Console.WriteLine("数字小于零");
goto End;
EqualToZero:
Console.WriteLine("数字等于零");
goto End;
GreaterThanZero:
Console.WriteLine("数字大于零");
goto End;
End:
Console.WriteLine("End...");
}
/// <summary>
/// 不使用goto正常输出使用示例
/// </summary>
public static void NonGotoGeneralUseExample(int num)
{
if (num < 0)
{
Console.WriteLine("数字小于零");
}
else if (num == 0)
{
Console.WriteLine("数字等于零");
}
else
{
Console.WriteLine("数字大于零");
}
Console.WriteLine("End...");
}
}
}