在上一节课中,我学习了类型转换、算术运算符、关系运算符、逻辑运算符以及各种分支结构,了解了这些语法的含义和执行过程。今天的课程聚焦于如何让我们编写的程序更具健壮性,减少出错的可能性。我学习了另一种分支结构 switch - case,并将其与上节课所学的分支结构进行了对比。此外,还学习了循环结构,这是目前所学内容中较为重要且复杂的一部分。为了更好地吸收和理解这些知识,我放慢了学习脚步,通过不断编写代码来巩固和加深理解。下面是我这节课所学的具体内容:
1. Abnormal capture
In nursing work, we often need to deal with various unexpected situations. For example, the thermometer may fail when measuring the patient's body temperature, and the tube may be blocked during infusion. Similarly, in programming, we also need to deal with various exceptions. C#provides exception handling mechanisms to help us handle these issues gracefully.
1. try-catch basic syntax
try
{
// 可能出现异常的代码
}
catch (Exception ex)
{
// 处理异常的代码
}
2. Practical application examples
The following is an example of entering patient vital sign data during nursing work:
try
{
Console.Write("请输入病人体温: ");
double temperature = Convert.ToDouble(Console.ReadLine());
if (temperature < 35 || temperature > 42)
{
throw new Exception("体温数据异常,请重新检查");
}
Console.Write("请输入收缩压: ");
int systolicPressure = Convert.ToInt32(Console.ReadLine());
if (systolicPressure < 60 || systolicPressure > 200)
{
throw new Exception("血压数据异常,请重新测量");
}
Console.WriteLine($"记录的体温为: {temperature}°C");
Console.WriteLine($"记录的收缩压为: {systolicPressure}mmHg");
}
catch (FormatException)
{
Console.WriteLine("输入格式错误,请输入有效的数字");
}
catch (OverflowException)
{
Console.WriteLine("输入的数值超出范围");
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
// 可以在这里记录错误日志
}
finally
{
Console.WriteLine("数据录入操作完成");
// 无论是否发生异常,都会执行的清理工作
}
3. Common exception types
In the nursing information system, we often encounter the following abnormalities:
-
-
- FormatException **: Thrown when the entered data format is incorrect, such as entering letters instead of numbers
-
-
-
- OverflowException **: Thrown when the value exceeds the type range
-
-
-
- ArgumentException **: Thrown when the parameter value does not meet the requirements
-
-
-
- NullReferenceException **: Thrown when attempting to access an empty object
-
4. custom exception
Sometimes we need to throw custom exceptions based on business logic:
public class VitalSignException : Exception
{
public VitalSignException(string message) : base(message)
{
}
}
try
{
int heartRate = 150;
if (heartRate > 120)
{
throw new VitalSignException("心率异常升高,需要立即处理!");
}
}
catch (VitalSignException ex)
{
Console.WriteLine($"生命体征异常: {ex.Message}");
// 这里可以添加紧急处理流程
}
5. best practices
- Catch only expected exceptions, avoid catching all exceptions
- Handling exceptions at the appropriate level
- Record anomaly information for subsequent analysis
- Use the finally block for cleanup
- Provide meaningful error information
2. Scope of variables
The scope of a variable refers to the range within which the variable can be used. Just like in a hospital, nurses in different departments can only view patient information in their own departments, variables also have limitations on their scope of use.
1. local variables
The scope of a local variable starts with the bracket in which it is declared and ends with the closing bracket corresponding to that bracket. This is like a temporary record sheet used inside the nurse station:
void RecordPatientVitals()
{
// temperature 只在这个方法内有效
double temperature = 36.5;
if (temperature > 37.3)
{
// fever 只在if语句块内有效
string fever = "发热";
Console.WriteLine(fever);
}
// 这里无法使用 fever 变量
{
// pulse 只在这个代码块内有效
int pulse = 80;
}
// 这里无法使用 pulse 变量
}
2. Class-level variables (member variables)
The scope of class-level variables is visible throughout the class, just as a ward's nursing record sheet can be accessed by nurses in all shifts:
public class Patient
{
// 这些变量在整个类中都可以访问
private string patientName;
private int patientAge;
private string bedNumber;
public void AdmitPatient(string name, int age)
{
patientName = name; // 可以访问类级变量
patientAge = age; // 可以访问类级变量
}
public void AssignBed(string bed)
{
bedNumber = bed; // 可以访问类级变量
}
}
3. Global variables (static variables)
Static variables can be accessed by the entire program, similar to general hospital rules and regulations:
public class HospitalConstants
{
// 这些静态变量可以在任何地方访问
public static readonly double NORMAL_TEMPERATURE = 37.0;
public static readonly int NORMAL_SYSTOLIC_PRESSURE = 120;
public static readonly int NORMAL_DIASTOLIC_PRESSURE = 80;
}
public class NursingRecord
{
public void CheckTemperature(double temperature)
{
// 可以在任何类中访问 HospitalConstants 的静态变量
if (temperature > HospitalConstants.NORMAL_TEMPERATURE)
{
Console.WriteLine("体温偏高");
}
}
}
4. variable masking
When a local variable and a class-level variable have the same name, the local variable "masks" the class-level variable:
public class VitalSigns
{
private double temperature = 36.5; // 类级变量
public void UpdateTemperature(double temperature) // 参数
{
// 这里的 temperature 指的是参数,而不是类级变量
Console.WriteLine($"新的体温: {temperature}");
// 使用 this 关键字访问类级变量
this.temperature = temperature;
}
}
5. Best practices for scope
- The scope of variables should be as small as possible to reduce the possibility of errors
- Avoid using global variables because they can be modified by any code
- Use meaningful variable names to reflect their purpose
- Release resources that are no longer in use in a timely manner
- Pay attention to the life cycle of your variables and avoid accessing variables that are out of scope
三、switch - case 语句
在护理工作中,我们经常需要根据不同的情况作出不同的处理决定。switch - case 语句就像我们在护理工作中使用的标准处理流程,根据不同的情况选择相应的处理方案。
1. supported types
switch 语句支持以下类型的表达式:
- 整数类型(
int、long、byte等) - 字符类型(
char) - 字符串类型(
string) - 枚举类型(
enum) - 布尔类型(
bool)- C# 7.0 及以上版本 - Pattern matching (C #7.0 and above)
- type mode
- constant pattern
- var model
- Attribute mode (C #8.0 and above)
Example:
// 枚举类型示例
enum PatientStatus
{
Normal,
Fever,
Pain,
Critical
}
PatientStatus status = PatientStatus.Fever;
switch (status)
{
case PatientStatus.Normal:
Console.WriteLine("继续观察");
break;
case PatientStatus.Fever:
Console.WriteLine("进行降温处理");
break;
case PatientStatus.Pain:
Console.WriteLine("给予止痛治疗");
break;
case PatientStatus.Critical:
Console.WriteLine("立即通知医生");
break;
}
// 模式匹配示例(C# 7.0+)
object obj = "护理记录";
switch (obj)
{
case string s:
Console.WriteLine($"这是一个字符串:{s}");
break;
case int n:
Console.WriteLine($"这是一个整数:{n}");
break;
case null:
Console.WriteLine("对象为空");
break;
default:
Console.WriteLine("未知类型");
break;
}
2. basic syntax
switch (表达式)
{
case 常量1:
语句1;
break;
case 常量2:
语句2;
break;
default:
默认语句;
break;
}
3. Practical application examples
For example, different nursing measures are taken based on the patient's pain level:
int painLevel = 3; // 疼痛等级(0-10)
switch (painLevel)
{
case 0:
Console.WriteLine("无需止痛处理");
break;
case 1:
case 2:
case 3:
Console.WriteLine("建议非药物治疗,如按摩、热敷等");
break;
case 4:
case 5:
case 6:
Console.WriteLine("考虑口服止痛药");
break;
case 7:
case 8:
case 9:
case 10:
Console.WriteLine("需要立即处理,考虑注射止痛药");
break;
default:
Console.WriteLine("无效的疼痛等级");
break;
}
4. precautions
-
-
- Importance of break statements **: Each case branch must end with a break, otherwise execution of the next case will continue
-
-
-
- Merging of cases **: Multiple cases can share the same processing logic, such as pain level grouping in the example
-
-
-
- default branch **: Used to handle all unspecified situations, similar to emergency plans in care
-
5. Comparison of branch structures
The difference between if, if-else and switch
-
-
- Condition type **:
if:可以判断任何返回布尔值的条件if-else:同样可以判断任何布尔条件,但提供了替代方案switch:只能判断相等性,且要求使用常量表达式
-
-
-
- Applicable scenarios **:
if:适合单一条件判断if-else:适合两种及以上情况的判断switch:适合多个等值条件的判断
-
-
-
- Performance considerations **:
- When there are fewer branches, the three perform similar
- 当分支较多时,
switch通常比多个if-else性能更好,因为编译器会优化成跳转表
-
Detailed comparison of if-else if and switch-case
// 使用 if-else if
if (patientStatus == "发热")
{
Console.WriteLine("进行物理降温");
CheckTemperature();
}
else if (patientStatus == "疼痛")
{
Console.WriteLine("评估疼痛等级");
PainAssessment();
}
else if (patientStatus == "出血")
{
Console.WriteLine("立即止血");
StopBleeding();
}
else
{
Console.WriteLine("继续观察");
}
// 使用 switch-case
switch (patientStatus)
{
case "发热":
Console.WriteLine("进行物理降温");
CheckTemperature();
break;
case "疼痛":
Console.WriteLine("评估疼痛等级");
PainAssessment();
break;
case "出血":
Console.WriteLine("立即止血");
StopBleeding();
break;
default:
Console.WriteLine("继续观察");
break;
}
Main differences:
-
-
- Grammar structure **:
if-else if结构更灵活,可以处理复杂的条件判断switch-case结构更规范,代码更整洁
-
-
-
- Conditions and Restrictions **:
if-else if可以使用任何条件表达式switch-case只能使用相等性比较
-
-
-
- Implementation process **:
if-else if会逐个判断条件switch-case直接跳转到匹配的 case
-
-
-
- Code maintenance **:
- 当分支较多时,
switch-case的可读性和可维护性通常更好 if-else if适合处理复杂的逻辑判断
-
-
-
- Performance considerations **:
- 对于大量分支的情况,
switch-case通常性能更好 - For a small number of branches, there is little difference in performance between the two
-
6. use recommendations
- When you need to perform different operations based on different values of a variable, use switch-case first
- When there are more branches, switch-case is usually more readable than if-else
- For complex conditional judgments (such as range judgments), if-else is more appropriate
- Ensure that all possible situations have corresponding processing logic
4. Circular structure
In nursing work, we often need to repeat certain operations, such as measuring vital signs every hour or giving rounds to each patient in the ward. In programming, loop structures are used to handle this repetitive work.
1. while loop
while 循环会在条件为真时重复执行代码块。就像我们在护理工作中,需要持续监测病人的体温直到体温恢复正常:
double temperature = 39.0;
while (temperature > 37.3)
{
Console.WriteLine($"当前体温:{temperature}°C,需要继续降温");
// 模拟降温处理
temperature -= 0.2;
Console.WriteLine("进行物理降温...");
Thread.Sleep(1000); // 模拟等待一段时间
}
Console.WriteLine("体温已恢复正常");
2. do-while loop
do-while 循环至少会执行一次代码块,然后再判断条件。这类似于我们必须先给病人测量一次体温,然后才能决定是否需要继续监测:
int painLevel;
do
{
Console.WriteLine("请评估疼痛等级(0-10):");
painLevel = Convert.ToInt32(Console.ReadLine());
if (painLevel > 0)
{
Console.WriteLine("实施止痛措施...");
// 进行止痛处理
}
} while (painLevel > 3); // 当疼痛等级大于3时继续监测
3. for loop
for 循环通常用于知道具体循环次数的情况。比如查房时需要检查每个病床的病人:
int bedCount = 6; // 假设病房有6张床
for (int bedNumber = 1; bedNumber <= bedCount; bedNumber++)
{
Console.WriteLine($"正在查看{bedNumber}号床的病人");
// 进行查房操作
CheckPatientStatus(bedNumber);
}
4. foreach loop
foreach 循环用于遍历集合中的每个元素。例如,查看所有待处理的护理任务:
List<string> nursingTasks = new List<string>
{
"测量生命体征",
"更换药液",
"伤口护理",
"病历记录"
};
foreach (string task in nursingTasks)
{
Console.WriteLine($"执行护理任务:{task}");
// 执行护理任务
PerformNursingTask(task);
}
5. loop control statement
-
-
- break statement **: Exit the loop immediately
-
while (true)
{
double temperature = MeasureTemperature();
if (temperature <= 37.3)
{
Console.WriteLine("体温正常,停止监测");
break; // 体温正常时退出循环
}
// 继续监测
}
-
-
- continue statement **: Skip the rest of the current loop and continue with the next loop
-
for (int bedNumber = 1; bedNumber <= 6; bedNumber++)
{
if (IsBedEmpty(bedNumber))
{
continue; // 如果床位空着,跳过当前循环
}
// 对有病人的床位进行护理操作
ProvideNursing(bedNumber);
}
6. Best practices for recycling
-
-
- Select the right cycle type **:
- 不确定循环次数时使用
while - 至少需要执行一次时使用
do-while - 知道具体循环次数时使用
for - 遍历集合时使用
foreach
-
-
-
- Avoid infinite loops **:
- Ensure that the loop condition eventually becomes false
- Use the break statement to exit the loop when appropriate
-
-
-
- Performance considerations **:
- Avoid unnecessary calculations in the loop
- Reduce the number of layers of loop nesting as much as possible
- Use continue statements rationally to skip unnecessary operations
-
-
-
- Code readability **:
- Use meaningful loop variable names
- Add appropriate comments explaining the purpose of the cycle
- Keep the cycle simple
-
-
-
- Exception handling **:
- Add appropriate exception handling to the loop
- Consider possible error situations during the cycle
-
7. Circular application scenarios
-
-
- Data processing **:
-
List<Patient> patients = GetAllPatients();
foreach (Patient patient in patients)
{
UpdatePatientRecord(patient);
}
-
-
- Input verification **:
-
string input;
do
{
Console.Write("请输入有效的体温数值(35-42):");
input = Console.ReadLine();
} while (!IsValidTemperature(input));
-
-
- Timing tasks **:
-
while (isNightShift)
{
// 每两小时查房一次
CheckPatients();
Thread.Sleep(TimeSpan.FromHours(2));
}
Through these cyclic structures, we can handle repetitive nursing work more efficiently and improve work efficiency and accuracy. In programming, the rational use of loop structures can make our code more concise and easier to maintain.
5. Program debugging
In nursing work, we often need to check the implementation of medical orders and check whether nursing records are accurate. Similarly, in programming, we also need to check whether the program performs as expected. Program debugging is such a process of verification and error correction.
1. debugging method
-
-
- F11 station-by-statement debugging (single-step debugging)**
- Execute the code line by line to view the execution status of each step in detail
- It's like we check the execution process step by step
- Line of code suitable for locating specific problems
-
-
-
- F10 process-by-process debugging **
- Executes code in units of procedures, skipping detailed execution within functions
- Similar to focusing on key items during ward rounds and temporarily skipping minor details
- Suitable for quickly understanding the overall program execution process
-
-
-
- Breakpoint debugging **
- Set breakpoints on key lines of code, and the program will pause at the breakpoint
- It's like focusing on checking the conditions of certain special patients before changing shifts
- Easily view variable values and program status in specific locations
-
2. Debugging examples
public class PatientMonitor
{
public void MonitorVitalSigns(Patient patient)
{
// 设置断点,检查病人基本信息
var temperature = MeasureTemperature(patient);
if (temperature > 37.3)
{
// 使用F11可以进入函数内部查看测量过程
// 使用F10可以跳过处理函数的内部细节
HandleFever(patient, temperature);
}
// 继续监测其他生命体征
CheckBloodPressure(patient);
CheckHeartRate(patient);
}
}
3. debugging technique
-
-
- Set breakpoints reasonably **
- Set breakpoints at code that may go wrong
- Set breakpoints at the starting point of critical business logic
- Set breakpoints at exception handling code
-
-
-
- Use the monitoring window **
- Add key variables to the monitoring window
- Observe changes in variable values in real time
- Verify the correctness of data processing
-
-
-
- Conditional Breakpoint **
- Set breakpoints that only trigger under certain conditions
- For example, pause procedures only when body temperature exceeds 39 degrees
-
summary
In this lesson, we learned the following important things:
-
-
- Exception handling **
- Use of try-catch structure
- Methods to handle different types of exceptions
- Creation and use of custom exceptions
-
-
-
- Variable scope **
- Differences between local variables, class-level variables and static variables
- variable masking phenomenon
- Best practices for scope
-
-
-
- Branch structure **
- Basic usage of switch-case statements
- Supported data types and pattern matching
- Comparison and choice with if-else structure
-
-
-
- Circular structure **
- Usage scenarios for while, do-while, for, foreach
- Loop control statements (break, continue)
- Best practices and performance considerations for cycling
-
-
-
- Program debugging **
- Step and process by process debugging
- Setting and using breakpoints
- Effective use of debugging tools
-
As a learner who has turned from nurse to program development, I have found many similarities between programming concepts and nursing work. Just as nursing work requires strict operating procedures, clear records and timely exception handling, programming also requires standardized code structure, clear logic and complete error handling.
Through the study of these basic knowledge, I gradually established programming thinking and was able to better understand and solve programming problems. In the following study, I will continue to deeply explore more features of C#programming to lay a solid foundation for becoming an excellent developer.