(6)From Nurse to C#Developer-Basic Advances: Program Control and Data Structure

(6)From Nurse to C#Developer-Basic Advances: Program Control and Data Structure

On the sixth day of C#programming, I learned loop control, ternary expressions, constants, enumerations, structures, arrays, and methods. As a developer who turned from the nursing industry, I combine these programming concepts with nursing work experience to help me better understand and remember them.

最后更新 3/9/2025 8:49 PM
勇敢的天使
预计阅读 25 分钟
分类
share courses
专题
From Nurse to C#Developer
标签
.NET C# Change career development programming program control

preface

This is my sixth learning note in my learning journey from nurse to C#developer. Today I learned more about program control and data structure, which helped me better organize and manage the data and processes in the program.

continue statement

The Continue statement is used to immediately end this loop and determine the loop conditions. If it is true, enter the next loop, otherwise exit the loop. This reminds me of how in nursing work, when a certain step doesn't apply to a particular patient, we skip that step and move on to other parts of the care plan.

Let me illustrate the use of Continue with an example:

// 模拟病房巡视,跳过空床位
for (int bedNumber = 1; bedNumber <= 10; bedNumber++)
{
    // 假设4号床和7号床是空床位
    if (bedNumber == 4 || bedNumber == 7)
    {
        Console.WriteLine($"{bedNumber}号床是空床位,跳过检查");
        continue; // 跳过本次循环,直接进入下一次
    }

    // 执行病人检查流程
    Console.WriteLine($"正在检查{bedNumber}号床的病人");
    // 其他检查代码...
}

In this example, the loop traverses beds 1 to 10. When empty beds (Nos. 4 and 7) are encountered, the continue statement is used to skip the current loop, and the subsequent patient examination process is not executed, and the next bed is directly checked.

Another example is processing patient data:

// 处理患者体温数据,跳过无效数据
double[] temperatures = { 36.5, 37.2, 0, 36.8, 39.1, 0, 36.9 };
double sum = 0;
int validCount = 0;

for (int i = 0; i < temperatures.Length; i++)
{
    // 跳过记录为0的无效数据
    if (temperatures[i] == 0)
    {
        Console.WriteLine($"第{i+1}个体温数据无效,跳过");
        continue;
    }

    // 处理有效数据
    sum += temperatures[i];
    validCount++;
    Console.WriteLine($"记录有效体温: {temperatures[i]}°C");
}

// 计算平均体温
double average = sum / validCount;
Console.WriteLine($"患者平均体温: {average:F1}°C");

In nursing work, the continue statement is like a process where we decide to skip certain inapplicable steps based on the patient's specific conditions when performing a series of standard nursing operations and go directly to the next step. This flexibility allows us to handle situations more efficiently.

ternary expression

三元表达式的语法为:表达式1 ? 表达式2 : 表达式3

  • Expression 1 is generally a relational expression
  • If the value of Expression 1 is true, then the value of Expression 2 is the value of the entire ternary expression
  • If the value of Expression 1 is false, then the value of Expression 3 is the value of the entire ternary expression

It should be noted that the result type of Expression 2 must be consistent with the result type of Expression 3, and it must also be consistent with the result type of the entire ternary expression.

Let me illustrate the use of ternary expressions with a few examples:

// 例1:根据体温判断是否发热
double temperature = 37.8;
string result = temperature >= 37.5 ? "患者发热" : "体温正常";
Console.WriteLine(result); // 输出:患者发热

The above example is equivalent to the following if-else statement:

double temperature = 37.8;
string result;
if (temperature >= 37.5)
{
    result = "患者发热";
}
else
{
    result = "体温正常";
}
Console.WriteLine(result);

As you can see, ternary expressions make the code more concise.

Let's take a slightly more complicated example:

// 例2:根据血压值返回不同的护理建议
int systolicBP = 145; // 收缩压
string advice = systolicBP >= 140 ?
                (systolicBP >= 180 ? "紧急处理,立即降压" : "需观察,按医嘱用药") :
                "血压正常,继续监测";
Console.WriteLine(advice); // 输出:需观察,按医嘱用药

In this example, we use nested ternary expressions to handle multiple conditions. When the systolic blood pressure exceeds 140, it is further judged whether the emergency state reaches 180 or above.

ternary expressions are also useful when calculating values:

// 例3:计算药物剂量(根据体重)
double weight = 65.5; // 患者体重(kg)
double baseDose = 5.0; // 基础剂量(mg)
double doseMultiplier = weight < 50 ? 0.8 : (weight > 80 ? 1.2 : 1.0);
double finalDose = baseDose * doseMultiplier;

Console.WriteLine($"患者体重: {weight}kg");
Console.WriteLine($"剂量调整系数: {doseMultiplier}");
Console.WriteLine($"最终药物剂量: {finalDose}mg");

Similar quick judgment scenarios are common in my nursing work. For example, assigning different levels of care based on various indicators of the patient, or deciding what measures to take based on the evaluation results. ternary expressions help me express these decision logic succinctly in my code.

Everything if-else can do can be done with ternary expressions, but when the logic is too complex, it may be clearer to use traditional if-else for code readability.

constant

Declaration syntax for constants:

const 变量类型 变量名 = 值

Once declared, constants cannot be reassigned. In nursing care, this is similar to some fixed medical parameters, such as normal body temperature ranges, standard blood pressure values, etc.

Let me illustrate the use of constants with a few examples:

// 定义医疗相关常量
const double NORMAL_BODY_TEMP = 36.5;      // 正常体温参考值
const int NORMAL_SYSTOLIC_BP = 120;        // 正常收缩压参考值
const int NORMAL_DIASTOLIC_BP = 80;        // 正常舒张压参考值
const int MIN_ADULT_HEART_RATE = 60;       // 成人最低心率
const int MAX_ADULT_HEART_RATE = 100;      // 成人最高心率
const string HOSPITAL_NAME = "仁爱医院";    // 医院名称

// 使用常量
double patientTemp = 38.2;
if (patientTemp > NORMAL_BODY_TEMP + 1.0)
{
    Console.WriteLine("患者体温明显升高,需要医生评估");
}

int patientSystolicBP = 135;
if (patientSystolicBP > NORMAL_SYSTOLIC_BP)
{
    Console.WriteLine("患者血压偏高");
}

Console.WriteLine($"欢迎来到{HOSPITAL_NAME}!");

Constants are usually named in all capital letters, separated by underscores, which is a common naming convention.

Benefits of constants:

  1. Improve code readability-use meaningful names instead of magic numbers (such as 36.5 instead of body temperature)
  2. Easy to maintain-if you need to modify a value, you only need to modify one constant definition
  3. Avoid errors-Prevent accidental modifications to these values in your code

Attempting to reassign constants will cause compilation errors:

const int ADMISSION_AGE = 18;
ADMISSION_AGE = 16; // 编译错误:无法给常量赋值

In my nursing work, there are many fixed standards and thresholds, such as normal ranges for vital signs, upper limits on drug doses, standard procedures for treatment, etc. Using constants in programming reminds me of these medical standards and helps me better understand and remember the concept.

enumeration

Enumeration can standardize our development, and the syntax is as follows:

[public] enum 枚举名
{
    值1,
    值2,
    值3,
    ...
}

public is an access modifier that means public, public, and can be accessed anywhere. Enumeration names must comply with Pascal naming conventions. Declaring the enumeration below the namespace and outside the class means that all classes in the namespace can use the enumeration.

Enumeration is essentially a variable type, similar to int, double, string, decimal, etc., except that the way enum is declared, assigned, and used is different from ordinary variable types. We can convert variables of enumeration types to int types and string types.

Let me illustrate the use of enumerations with an example from a medical scenario:

// 定义护理评估中的疼痛等级枚举
public enum PainLevel
{
    None,           // 0 - 无疼痛
    Mild,           // 1 - 轻度疼痛
    Moderate,       // 2 - 中度疼痛
    Severe,         // 3 - 严重疼痛
    Unbearable      // 4 - 难以忍受的疼痛
}

// 定义护理任务优先级枚举
public enum NursingPriority
{
    Routine = 1,    // 常规护理
    Urgent = 2,     // 紧急护理
    Emergency = 3   // 危急情况
}

// 定义患者风险评估结果枚举
public enum RiskAssessment
{
    Low = 10,       // 低风险
    Medium = 20,    // 中等风险
    High = 30       // 高风险
}

// 在程序中使用枚举
class Program
{
    static void Main(string[] args)
    {
        // 1. 基本枚举使用
        PainLevel patientPain = PainLevel.Moderate;
        Console.WriteLine($"患者疼痛等级: {patientPain}"); // 输出: 患者疼痛等级: Moderate

        // 2. 根据疼痛等级确定护理优先级
        NursingPriority priority;
        if (patientPain >= PainLevel.Severe)
        {
            priority = NursingPriority.Urgent;
        }
        else if (patientPain == PainLevel.None)
        {
            priority = NursingPriority.Routine;
        }
        else
        {
            priority = NursingPriority.Routine;
        }

        Console.WriteLine($"护理优先级: {priority}"); // 输出: 护理优先级: Routine

        // 3. 使用枚举进行决策
        switch (patientPain)
        {
            case PainLevel.None:
                Console.WriteLine("无需止痛药物");
                break;
            case PainLevel.Mild:
                Console.WriteLine("考虑使用非处方止痛药");
                break;
            case PainLevel.Moderate:
                Console.WriteLine("按医嘱给予口服止痛药");
                break;
            case PainLevel.Severe:
            case PainLevel.Unbearable:
                Console.WriteLine("立即联系医生,考虑注射止痛药");
                break;
            default:
                Console.WriteLine("无效的疼痛评估");
                break;
        }

        // 4. 枚举与整数互相转换
        int painValue = (int)patientPain;
        Console.WriteLine($"疼痛数值: {painValue}"); // 输出: 疼痛数值: 2

        // 整数转换为枚举
        PainLevel convertedPain = (PainLevel)3;
        Console.WriteLine($"转换后的疼痛等级: {convertedPain}"); // 输出: 转换后的疼痛等级: Severe

        // 5. 枚举转换为字符串
        string painString = patientPain.ToString();
        Console.WriteLine($"疼痛描述: {painString}"); // 输出: 疼痛描述: Moderate

        // 6. 字符串转换为枚举
        PainLevel parsedPain = (PainLevel)Enum.Parse(typeof(PainLevel), "Mild");
        Console.WriteLine($"解析后的疼痛等级: {parsedPain}"); // 输出: 解析后的疼痛等级: Mild

        // 7. 尝试转换数字字符串
        PainLevel numericPain = (PainLevel)Enum.Parse(typeof(PainLevel), "1");
        Console.WriteLine($"数字解析的疼痛等级: {numericPain}"); // 输出: 数字解析的疼痛等级: Mild

        // 8. 处理可能发生的异常
        try
        {
            PainLevel invalidPain = (PainLevel)Enum.Parse(typeof(PainLevel), "Critical");
            Console.WriteLine($"解析结果: {invalidPain}");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("无法将'Critical'转换为有效的疼痛等级,因为枚举中没有此值");
        }

        // 9. 获取枚举的所有可能值
        Console.WriteLine("所有可能的疼痛等级:");
        foreach (PainLevel level in Enum.GetValues(typeof(PainLevel)))
        {
            Console.WriteLine($"- {level} ({(int)level})");
        }
    }
}

In this example, we can see:

      • Enumeration definitions **: We define three care-related enumeration types (pain level, care priority, and risk assessment)
      • Default value **: If no value is specified, the value of the first member of the enumeration is 0, and the values of subsequent members are incremented by 1
  1. 自定义值:我们可以为枚举成员指定自定义的整数值,如NursingPriorityRiskAssessment
      • Enumeration comparison **: You can use operators such as greater than and equal to compare different values of the same enumeration type
      • Type conversion **: Enumerations can be converted to int and string
      • Error handling **: An exception is thrown when trying to convert a non-existent string to an enumeration value

Similar grading systems can be seen everywhere in my nursing work. For example:

  • Pain Assessment Scale (0 - 10 points)
  • Pressure sore risk score (Braden scale)
  • Fall risk level
  • Phlebitis grading
  • Drug classification system

Using enumerations makes the code more standardized and easy to understand, avoiding the use of "magic numbers"(such as using 1, 2, and 3 directly without stating their meaning). At the same time, the compiler also checks for type safety to prevent us from misusing enumeration values.

structure

Structures can help us declare multiple different types of variables at once, usually written under namespaces. The syntax is as follows:

[public] struct 结构名(符合Pascal)
{
    成员; //字段
}

Unlike variables that can only hold one value during program execution, structures can store multiple values. Let me illustrate the use of structure with an example from a nursing scenario:

// 定义患者生命体征结构
public struct VitalSigns
{
    public double Temperature;      // 体温
    public int HeartRate;          // 心率
    public int SystolicBP;         // 收缩压
    public int DiastolicBP;        // 舒张压
    public int RespiratoryRate;    // 呼吸频率
    public int OxygenSaturation;   // 血氧饱和度
}

// 定义患者基本信息结构
public struct PatientInfo
{
    public string Name;            // 姓名
    public int Age;                // 年龄
    public char Gender;            // 性别('M' 或 'F')
    public string ID;              // 病历号
    public string Ward;            // 病区
    public int BedNumber;          // 床号
    public VitalSigns Vitals;      // 生命体征
}

// 使用结构的示例
class Program
{
    static void Main(string[] args)
    {
        // 创建并初始化一个患者信息
        PatientInfo patient;
        patient.Name = "张三";
        patient.Age = 45;
        patient.Gender = 'M';
        patient.ID = "P20250305001";
        patient.Ward = "内科";
        patient.BedNumber = 12;

        // 设置患者生命体征
        patient.Vitals.Temperature = 37.2;
        patient.Vitals.HeartRate = 78;
        patient.Vitals.SystolicBP = 130;
        patient.Vitals.DiastolicBP = 85;
        patient.Vitals.RespiratoryRate = 16;
        patient.Vitals.OxygenSaturation = 98;

        // 显示患者信息
        DisplayPatientInfo(patient);

        // 评估生命体征
        AssessVitalSigns(patient.Vitals);
    }

    // 显示患者信息的方法
    static void DisplayPatientInfo(PatientInfo patient)
    {
        Console.WriteLine("患者基本信息:");
        Console.WriteLine($"姓名: {patient.Name}");
        Console.WriteLine($"年龄: {patient.Age}岁");
        Console.WriteLine($"性别: {(patient.Gender == 'M' ? "男" : "女")}");
        Console.WriteLine($"病历号: {patient.ID}");
        Console.WriteLine($"病区: {patient.Ward}");
        Console.WriteLine($"床号: {patient.BedNumber}号");
        Console.WriteLine("\n生命体征:");
        Console.WriteLine($"体温: {patient.Vitals.Temperature}°C");
        Console.WriteLine($"心率: {patient.Vitals.HeartRate}次/分");
        Console.WriteLine($"血压: {patient.Vitals.SystolicBP}/{patient.Vitals.DiastolicBP} mmHg");
        Console.WriteLine($"呼吸: {patient.Vitals.RespiratoryRate}次/分");
        Console.WriteLine($"血氧: {patient.Vitals.OxygenSaturation}%");
    }

    // 评估生命体征的方法
    static void AssessVitalSigns(VitalSigns vitals)
    {
        Console.WriteLine("\n生命体征评估:");

        // 评估体温
        if (vitals.Temperature > 37.5)
            Console.WriteLine("- 体温偏高,需要监测");

        // 评估心率
        if (vitals.HeartRate < 60 || vitals.HeartRate > 100)
            Console.WriteLine("- 心率异常,需要关注");

        // 评估血压
        if (vitals.SystolicBP >= 140 || vitals.DiastolicBP >= 90)
            Console.WriteLine("- 血压偏高,建议复查");

        // 评估呼吸
        if (vitals.RespiratoryRate < 12 || vitals.RespiratoryRate > 20)
            Console.WriteLine("- 呼吸频率异常,需要观察");

        // 评估血氧
        if (vitals.OxygenSaturation < 95)
            Console.WriteLine("- 血氧偏低,考虑给氧");
    }
}

In this example, we can see:

  1. 结构的定义:我们定义了两个结构(VitalSignsPatientInfo),用于存储患者的相关信息
  2. 结构的嵌套PatientInfo结构中包含了VitalSigns结构,展示了结构的嵌套使用
      • Initialization of structure **: Shows how to create structure variables and set their field values
      • Structure as Parameter **: Shows how to pass structure as method parameters
      • Practical application of structure **: Demonstrate the application of structure in actual scenarios by evaluating vital signs

This way of organizing data reminds me of the medical record system in nursing work. In the medical record, we also organize various patient information (basic information, vital signs, examination results, etc.) in a specific format. Using structures can help us better manage this related data and make the code more organized and maintainable.

array

Arrays allow us to store multiple variables of the same type at once. Grammar:

数组类型[] 数组名 = new 数组类型[数组长度]

例如:int[] nums = new int[10];

When I wrote the above line of code, I opened up 10 consecutive spaces in memory. We call each piece of space an element of the array. If you want to access an element in an array, you need to access it through the index or index of the element. The index of the last element in the array is the length minus one.

Let me illustrate the use of arrays through a few examples from nursing work:

// 例1:记录一周的病房人数
int[] wardPatients = new int[7];  // 创建长度为7的数组

// 设置每天的病人数量
wardPatients[0] = 45;  // 星期一
wardPatients[1] = 42;  // 星期二
wardPatients[2] = 48;  // 星期三
wardPatients[3] = 50;  // 星期四
wardPatients[4] = 47;  // 星期五
wardPatients[5] = 40;  // 星期六
wardPatients[6] = 38;  // 星期日

// 计算平均住院人数
int totalPatients = 0;
for (int i = 0; i < wardPatients.Length; i++)
{
    totalPatients += wardPatients[i];
}
double averagePatients = (double)totalPatients / wardPatients.Length;
Console.WriteLine($"本周平均住院人数: {averagePatients:F1}人");

// 例2:数组的初始化方式
// 方式1:直接初始化
double[] temperatures = { 36.5, 36.8, 37.2, 36.9, 37.0 };

// 方式2:new关键字初始化
string[] medications = new string[] { "青霉素", "头孢", "阿莫西林", "布洛芬" };

// 方式3:先声明后赋值
int[] bedNumbers;
bedNumbers = new int[] { 101, 102, 103, 104, 105 };

// 例3:二维数组 - 记录多个病人一天的体温记录
double[,] patientTemps = new double[3, 4];  // 3个病人,每天4次体温记录

// 设置体温数据
patientTemps[0, 0] = 36.5;  // 1号病人早上
patientTemps[0, 1] = 36.8;  // 1号病人中午
patientTemps[0, 2] = 37.1;  // 1号病人下午
patientTemps[0, 3] = 36.9;  // 1号病人晚上

// 遍历二维数组
string[] timeSlots = { "早上", "中午", "下午", "晚上" };
for (int patient = 0; patient < 3; patient++)
{
    Console.WriteLine($"\n{patient + 1}号病人的体温记录:");
    for (int time = 0; time < 4; time++)
    {
        Console.WriteLine($"{timeSlots[time]}: {patientTemps[patient, time]}°C");
    }
}

// 例4:数组作为方法参数
static double CalculateAverageTemp(double[] temps)
{
    double sum = 0;
    foreach (double temp in temps)
    {
        sum += temp;
    }
    return sum / temps.Length;
}

// 调用方法
double[] patient1Temps = { 36.5, 36.8, 37.2, 36.9 };
double avgTemp = CalculateAverageTemp(patient1Temps);
Console.WriteLine($"患者平均体温: {avgTemp:F1}°C");

// 例5:数组的常见操作
string[] nurses = { "张护士", "李护士", "王护士", "赵护士" };

// 获取数组长度
Console.WriteLine($"护士数量: {nurses.Length}");

// 查找元素
string searchNurse = "李护士";
bool found = Array.IndexOf(nurses, searchNurse) != -1;
Console.WriteLine($"是否找到{searchNurse}: {found}");

// 数组排序
Array.Sort(nurses);
Console.WriteLine("排序后的护士名单:");
foreach (string nurse in nurses)
{
    Console.WriteLine(nurse);
}

// 数组复制
string[] backupNurses = new string[nurses.Length];
Array.Copy(nurses, backupNurses, nurses.Length);

In these examples, we can see:

      • Array creation **: There are many ways to create and initialize arrays
      • Array access **: Access array elements through index
      • Traversal of arrays **: Use a for loop or a foreach loop to traverse the array
      • Two-dimensional array **: Used to store more complex data structures
      • Arrays as arguments **: Arrays can be passed as arguments to methods
      • Common operations of arrays **: such as obtaining length, finding elements, sorting and copying, etc.

Once the length of an array is fixed, it cannot be changed. This reminds me of the drug distribution system in hospitals, where each drug has a fixed storage location and quantity. In nursing work, we often need to process a set of related data, such as:

  • Bed number in the ward
  • Patient's temperature record
  • drug list
  • Nursing shift arrangement
  • Vital signs monitoring data

Using arrays can effectively organize and manage this data, making our programs more structured and easier to maintain.

bubble sort

Bubble sort is used to arrange the elements in an array from largest to smallest or smallest to largest. For example, for arrays:

int[] nums = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

Here is a complete bubble-sorting example, sorting patients according to priority:

// 患者优先级数组(数字越大优先级越高)
int[] priorities = { 2, 5, 1, 7, 3, 8, 4, 6 };
string[] patientNames = { "张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十" };

Console.WriteLine("排序前的患者优先级:");
for (int i = 0; i < priorities.Length; i++)
{
    Console.WriteLine($"{patientNames[i]}: 优先级 {priorities[i]}");
}

// 冒泡排序(从高到低)
for (int i = 0; i < priorities.Length - 1; i++)
{
    for (int j = 0; j < priorities.Length - 1 - i; j++)
    {
        // 如果当前元素小于下一个元素,交换位置(降序排列)
        if (priorities[j] < priorities[j + 1])
        {
            // 交换优先级
            int tempPriority = priorities[j];
            priorities[j] = priorities[j + 1];
            priorities[j + 1] = tempPriority;

            // 同时交换对应的患者姓名
            string tempName = patientNames[j];
            patientNames[j] = patientNames[j + 1];
            patientNames[j + 1] = tempName;
        }
    }
}

Console.WriteLine("\n排序后的患者优先级(从高到低):");
for (int i = 0; i < priorities.Length; i++)
{
    Console.WriteLine($"{i+1}. {patientNames[i]}: 优先级 {priorities[i]}");
}

This is similar to triage and treating patients according to priority in nursing care. The idea of bubble sorting reminds me of the scene in the nurse station where we decide which patients to treat first based on the severity of the patient's condition.

method

Method is a mechanism for reusing a bunch of code. The syntax is as follows:

[public] static 返回值类型 方法名([参数列表])
{
    方法体;
}

Let me illustrate the use of the method with a few care-related examples:

class NursingProgram
{
    // 1. 无参数无返回值的方法
    public static void DisplayNursingProtocol()
    {
        Console.WriteLine("标准护理流程:");
        Console.WriteLine("1. 测量生命体征");
        Console.WriteLine("2. 检查输液情况");
        Console.WriteLine("3. 观察病情变化");
        Console.WriteLine("4. 记录护理记录");
    }

    // 2. 有参数有返回值的方法
    public static double CalculateIdealWeight(double height, char gender)
    {
        // 根据身高和性别计算理想体重
        if (gender == 'M' || gender == 'm')
        {
            return (height - 100) * 0.9;
        }
        else
        {
            return (height - 100) * 0.85;
        }
    }

    // 3. 多参数的方法
    public static double CalculateBMI(double weight, double height)
    {
        double heightInMeters = height / 100;
        return weight / (heightInMeters * heightInMeters);
    }

    // 4. 方法重载 - 评估体温
    public static string EvaluateTemperature(double temperature)
    {
        if (temperature < 35.5) return "低温";
        if (temperature <= 37.2) return "正常";
        if (temperature <= 38.0) return "低热";
        if (temperature <= 39.0) return "中度发热";
        return "高热";
    }

    // 同名方法,但参数不同
    public static string EvaluateTemperature(double temperature, bool isInfant)
    {
        if (isInfant)
        {
            // 婴儿体温标准略有不同
            if (temperature < 36.0) return "婴儿低温";
            if (temperature <= 37.5) return "婴儿正常体温";
            if (temperature <= 38.5) return "婴儿低热";
            return "婴儿高热";
        }
        else
        {
            return EvaluateTemperature(temperature); // 调用另一个重载方法
        }
    }

    // 5. 参数默认值
    public static string AssessBloodPressure(int systolic, int diastolic, bool detailed = false)
    {
        string result = "";
        if (systolic >= 140 || diastolic >= 90)
        {
            result = "血压偏高";
            if (detailed)
            {
                result += $" (收缩压:{systolic}, 舒张压:{diastolic})";
            }
        }
        else if (systolic < 90 || diastolic < 60)
        {
            result = "血压偏低";
            if (detailed)
            {
                result += $" (收缩压:{systolic}, 舒张压:{diastolic})";
            }
        }
        else
        {
            result = "血压正常";
        }
        return result;
    }

    // 6. 使用ref参数的方法
    public static void UpdateVitalSigns(ref double temperature, ref int pulse)
    {
        // 模拟新的测量值
        temperature = 37.2;
        pulse = 75;
    }

    // 主方法中使用这些方法
    static void Main(string[] args)
    {
        // 调用无参数方法
        DisplayNursingProtocol();

        // 计算理想体重
        double height = 170;
        char gender = 'F';
        double idealWeight = CalculateIdealWeight(height, gender);
        Console.WriteLine($"\n身高{height}cm的{(gender == 'F' ? "女" : "男")}性理想体重: {idealWeight:F1}kg");

        // 计算BMI
        double weight = 65;
        double bmi = CalculateBMI(weight, height);
        Console.WriteLine($"BMI指数: {bmi:F1}");

        // 使用方法重载评估体温
        double adultTemp = 38.5;
        double infantTemp = 37.8;
        Console.WriteLine($"\n成人体温{adultTemp}°C评估: {EvaluateTemperature(adultTemp)}");
        Console.WriteLine($"婴儿体温{infantTemp}°C评估: {EvaluateTemperature(infantTemp, true)}");

        // 使用默认参数
        int systolic = 145;
        int diastolic = 88;
        Console.WriteLine($"\n血压评估: {AssessBloodPressure(systolic, diastolic)}");
        Console.WriteLine($"血压评估(详细): {AssessBloodPressure(systolic, diastolic, true)}");

        // 使用ref参数
        double temp = 36.8;
        int pulse = 80;
        Console.WriteLine($"\n更新前 - 体温: {temp}°C, 脉搏: {pulse}次/分");
        UpdateVitalSigns(ref temp, ref pulse);
        Console.WriteLine($"更新后 - 体温: {temp}°C, 脉搏: {pulse}次/分");
    }
}

In these examples, we can see:

  1. 无参数方法DisplayNursingProtocol()展示了如何定义和使用无参数方法
  2. 有参数和返回值的方法CalculateIdealWeight()CalculateBMI()展示了如何处理输入参数并返回计算结果
  3. 方法重载EvaluateTemperature()展示了如何为同一个方法名提供不同的参数版本
  4. 默认参数AssessBloodPressure()展示了如何使用可选参数
  5. 引用参数UpdateVitalSigns()展示了如何使用 ref 参数在方法中修改变量的值

These methods remind me of standard operating procedures (SOPs) in nursing work:

  • Each care procedure has clear inputs (such as patient condition) and outputs (such as care measures)
  • The same care procedure may have different variations based on patient type (e.g. adults and children)
  • Certain nursing procedures can directly change the patient's status (such as drug administration)
  • Nursing assessment can be available in simple and detailed versions

By connecting the method to nursing practice, it is easier for me to understand and remember these programming concepts. The approach makes our code more organized, just like standardized care processes, improving work efficiency and accuracy.

return statement

The return statement has two functions:

  1. Returns the value to be returned in a method
  2. Immediately end the implementation of this method

Here is an example of using the return statement:

// 评估患者体温状态并给出护理建议
static string EvaluateTemperature(double temperature)
{
    // 低温
    if (temperature < 35.5)
    {
        return "体温过低,需保暖并监测";
    }

    // 正常体温
    if (temperature >= 35.5 && temperature <= 37.2)
    {
        return "体温正常,定时监测";
    }

    // 轻度发热
    if (temperature > 37.2 && temperature <= 38.0)
    {
        return "轻度发热,密切观察";
    }

    // 中度发热
    if (temperature > 38.0 && temperature <= 39.0)
    {
        return "中度发热,物理降温并考虑用药";
    }

    // 高热
    return "高热,紧急处理,立即通知医生";
}

// 在Main方法中调用
static void Main(string[] args)
{
    double[] patientTemps = { 36.5, 37.8, 39.2, 35.0, 38.5 };

    foreach (double temp in patientTemps)
    {
        string advice = EvaluateTemperature(temp);
        Console.WriteLine($"体温 {temp}°C: {advice}");
    }
}

In this example, once a condition is met, the return statement returns the corresponding recommendation and immediately ends execution of the method, without continuing to check subsequent conditions. This is similar to in nursing decisions, where once the patient's condition is determined, corresponding measures are taken immediately without considering other possibilities.

summary

As a nurse-turned-developer, I have found many similarities between programming and nursing work. By connecting these programming concepts with nursing experience, I was able to better understand and apply this knowledge and gradually grow into an excellent C#developer.

Keep Exploring

延伸阅读

更多文章
同标签 2/7/2026

Summary of experience in using AOT

From the very beginning of project creation, you should develop a good habit of conducting AOT release testing in a timely manner whenever new features are added or newer syntax is used.

继续阅读