(8)From Nurse to C#Developer-Data Types and Inheritance

(8)From Nurse to C#Developer-Data Types and Inheritance

This article will explain in detail important concepts such as namespaces, data types, string processing, inheritance, and collections in C#based on medical work scenarios to help medical staff better understand programming knowledge.

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

As a learner who has moved from the nursing industry to the field of programming, I have found that many programming concepts can be understood through medical work experience. This article will explain in detail several important concepts in C#based on the actual scenario of hospital information systems.

1. namespace

Namespaces are a way to organize and manage code, just like the organizational structure of a hospital. For example, the hospital is divided into different departments such as internal medicine, surgery, and nursing departments. Each department has its own responsibilities and management scope. Namespaces play a similar role in C#, which can:

  1. Avoid naming conflicts (just like different departments in a hospital can have nurses with the same name)
  2. Provide logical groupings (like hospital divisions)
  3. Control the access scope of codes (similar to hospital rights management)

1.1 Organization of namespaces

namespace HospitalSystem          // 整个医院系统
{
    namespace Administration     // 行政管理
    {
        // 人事管理、财务管理等类
    }

    namespace Clinical          // 临床医疗
    {
        namespace Internal      // 内科
        {
            // 内科相关类
        }

        namespace Surgery       // 外科
        {
            // 外科相关类
        }
    }

    namespace Nursing          // 护理部门
    {
        namespace WardManagement        // 病房管理
        {
            // 病房相关的类
        }

        namespace MedicationManagement  // 用药管理
        {
            // 用药相关的类
        }
    }
}

1.2 How to use namespaces

  1. Classes can be thought of as namespaces
  2. If there is no namespace for this class in the current project, we need to manually import the namespace where this class is located:
    • Use the mouse to click on the Visual Studio prompt
    • Use the shortcut key alt+shift+F10
    • Remember common namespaces and enter them manually

1.3 Using namespaces in your project

// 方法1:使用using导入
using HospitalSystem.Nursing;
using HospitalSystem.Pharmacy;

// 方法2:使用完整限定名称
HospitalSystem.Nursing.NursingRecord record = new HospitalSystem.Nursing.NursingRecord();

// 方法3:使用别名
using NurseRecord = HospitalSystem.Nursing.NursingRecord;

1.4 Project Reference Example

Reference another class in a project:

  1. Add references (such as adding HospitalCore.dll)
  2. reference namespace
using HospitalCore.Models;
using HospitalCore.Services;

2. value types and reference types

2.1 Detailed explanation of value types

Value types directly store the data itself, including:

  1. integer type

    • sbyte: 8-bit signed integer (-128 to 127)
    • byte: 8-bit unsigned integer (0 to 255)
    • short: 16-bit signed integer
    • ushort: 16-bit unsigned integer
    • int: 32-bit signed integer (most commonly used)
    • uint: 32-bit unsigned integer
    • long: 64-bit signed integer
    • ulong: 64-bit unsigned integer
  2. floating-point type

    • float: 32-bit single-precision floating point number (accurate to 6-9 bits)
    • double: 64-bit double precision floating point number (accurate to 15-17 bits)
    • decimal: 128-digit high-precision decimal (commonly used in financial calculations)
  3. Other value types

    • bool: Boolean value (true/false)
    • char: 16-bit Unicode character
    • enum: Enumeration types
    • struct: structure

Examples of applications in medical systems:

public struct VitalSigns
{
    public int HeartRate;        // 心率,范围通常60-100
    public decimal Temperature;   // 体温,精确到小数点后一位,如36.5
    public int BloodPressureHigh; // 收缩压,如120
    public int BloodPressureLow;  // 舒张压,如80
    public bool IsFever;          // 是否发烧

    // 枚举示例
    public enum TemperatureMethod
    {
        Oral,      // 口温
        Axillary,  // 腋温
        Rectal     // 肛温
    }
    public TemperatureMethod Method { get; set; }

    // 值类型的数据验证方法
    public bool IsNormal()
    {
        return HeartRate >= 60 && HeartRate <= 100
            && Temperature >= 36.0m && Temperature <= 37.2m
            && BloodPressureHigh >= 90 && BloodPressureHigh <= 140
            && BloodPressureLow >= 60 && BloodPressureLow <= 90;
    }
}

2.2 Detailed explanation of citation types

Reference types include:

  1. Class (class)

    • All custom classes
    • System predefined classes (such as String, Object, etc.)
  2. Interface

  3. delegation

  4. Array

    • Whether the element is a value type or a reference type, the array itself is a reference type
  5. String (string)

    • Although used frequently, string is a reference type
    • Has special immutable properties

Examples of medical systems:

public class PatientRecord
{
    // 基本信息
    public string PatientName { get; set; }
    public string IdNumber { get; set; }
    public DateTime DateOfBirth { get; set; }

    // 诊断信息(数组示例)
    public string[] Diagnoses { get; set; }

    // 用药信息(集合示例)
    public List<Medication> Medications { get; set; }

    // 生命体征记录(自定义类示例)
    public List<VitalSigns> VitalSignsHistory { get; set; }

    // 委托示例 - 用于生命体征异常通知
    public delegate void VitalSignsAlertHandler(string message);
    public event VitalSignsAlertHandler OnVitalSignsAlert;

    // 深拷贝示例
    public PatientRecord Clone()
    {
        var newRecord = new PatientRecord
        {
            PatientName = this.PatientName,
            IdNumber = this.IdNumber,
            DateOfBirth = this.DateOfBirth,
            Diagnoses = (string[])this.Diagnoses.Clone(),
            Medications = this.Medications.Select(m => m.Clone()).ToList(),
            VitalSignsHistory = this.VitalSignsHistory.Select(vs => vs.Clone()).ToList()
        };

        return newRecord;
    }
}

public class Medication
{
    public string Name { get; set; }
    public double Dosage { get; set; }

    // 深拷贝方法
    public Medication Clone()
    {
        return new Medication
        {
            Name = this.Name,
            Dosage = this.Dosage
        };
    }
}

public class VitalSigns
{
    public decimal Temperature { get; set; }
    public int HeartRate { get; set; }

    // 深拷贝方法
    public VitalSigns Clone()
    {
        return new VitalSigns
        {
            Temperature = this.Temperature,
            HeartRate = this.HeartRate
        };
    }
}

2.3 Detailed explanation of the difference between memory storage

In C#, memory is divided into two main areas: Stack and Heap:

  1. Stack

    • Store data of value type
    • Automatic management of memory allocation and release by the system
    • access speed
    • limited space
    • Store in last-in-first-out (LIFO) order
  2. Heap

    • Store actual data for reference types
    • Requires a garbage collector (GC) to manage memory
    • Large space but relatively slow access
    • More flexible memory allocation and reclamation

Example code:

public class MemoryExample
{
    public void DemonstrateMemoryUsage()
    {
        // 值类型示例
        int temperature = 37;         // 直接在栈上分配4字节
        bool isCritical = true;       // 直接在栈上分配1字节
        DateTime checkTime = DateTime.Now; // 虽然DateTime是struct,但仍在栈上分配

        // 引用类型示例
        string patientName = "张三";   // 在堆上分配字符串数据,栈上存储引用
        PatientRecord record = new PatientRecord(); // 对象在堆上,引用在栈上

        // 值类型复制示例
        int temp2 = temperature;      // 在栈上创建新的独立副本
        temp2 = 38;                   // 修改temp2不影响temperature
        Console.WriteLine($"原温度: {temperature}, 新温度: {temp2}"); // 37, 38

        // 引用类型复制示例
        PatientRecord record2 = record; // 复制引用,两个变量指向同一个堆上的对象
        record2.PatientName = "李四";   // 通过record2修改会影响record
        Console.WriteLine($"record的病人: {record.PatientName}"); // 输出"李四"

        // 字符串特例示例
        string str1 = "测试";
        string str2 = "测试";     // str2和str1指向同一个字符串对象(字符串池)
        string str3 = new string(new char[] { '测', '试' }); // 强制创建新对象

        // 数组示例
        int[] temperatures = new int[] { 36, 37, 38 }; // 数组对象在堆上,元素在数组对象内连续存储
        int[] temps2 = temperatures;  // 复制引用
        temps2[0] = 39;              // 修改temps2同时影响temperatures
    }

    // 值类型作为参数
    public void UpdateTemperature(int temp)
    {
        temp = 39; // 不会影响原始值
    }

    // 引用类型作为参数
    public void UpdatePatient(PatientRecord patient)
    {
        patient.PatientName = "王五"; // 会影响原始对象
    }
}

3. string processing

Strings are used very frequently in medical information systems, such as medical records, doctor's orders records, etc. C#provides rich string processing methods:

3.1 Characteristics of strings

  1. Immutability: Strings are immutable, and each modification creates a new string object
  2. String pool: The same string literals share the same object
  3. Can be thought of as a read-only array of type char

3.2 Detailed explanation of common string methods

public class NursingNoteProcessor
{
    public void ProcessNursingNotes()
    {
        // 护理记录示例
        string note = "  患者张三,男,62岁。\n" +
                     "警告:对青霉素过敏!\n" +
                     "  体温37.2℃,血压120/80mmHg  ";

        // 1. 基本字符串操作
        Console.WriteLine($"记录长度: {note.Length}");  // 获取字符串长度

        // 2. 空白处理
        string trimmed = note.Trim();      // 去除两端空格
        string trimStart = note.TrimStart(); // 去除开头空格
        string trimEnd = note.TrimEnd();    // 去除结尾空格

        // 3. 大小写转换
        string upper = note.ToUpper();     // 转大写(用于重要警告)
        string lower = note.ToLower();     // 转小写

        // 4. 查找操作
        bool hasAllergy = note.Contains("过敏");  // 检查是否包含某字符串
        int allergyIndex = note.IndexOf("过敏");  // 查找第一次出现的位置
        int lastIndex = note.LastIndexOf(",");   // 查找最后一次出现的位置

        // 5. 替换操作
        string replaced = note.Replace("警告", "【警告】");
        string noSpaces = note.Replace(" ", "");

        // 6. 字符串分割
        string[] lines = note.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string line in lines)
        {
            Console.WriteLine($"行内容: {line.Trim()}");
        }

        // 7. 子串提取
        int ageStart = note.IndexOf(",") + 1;
        int ageEnd = note.IndexOf("岁");
        string age = note.Substring(ageStart, ageEnd - ageStart);
        Console.WriteLine($"年龄: {age}"); // 输出: 62

        // 8. 字符串比较
        bool isEqual = note.Equals("其他记录", StringComparison.OrdinalIgnoreCase); // 忽略大小写比较
        bool startsWith = note.StartsWith("患者");  // 检查开头
        bool endsWith = note.EndsWith("mmHg");    // 检查结尾

        // 9. 字符串拼接
        string[] vitals = { "体温: 37.2℃", "血压: 120/80mmHg", "心率: 75次/分" };
        string summary = string.Join(", ", vitals);
        Console.WriteLine($"生命体征: {summary}");

        // 10. 字符串构建(处理大量字符串拼接)
        StringBuilder noteBuilder = new StringBuilder();
        noteBuilder.AppendLine("患者基本信息:");
        noteBuilder.AppendLine($"姓名:张三");
        noteBuilder.AppendLine($"年龄:{age}岁");
        noteBuilder.AppendLine($"生命体征:{summary}");
        string finalNote = noteBuilder.ToString();
    }
}

4. inheritance

Inheritance is one of the core concepts of object-oriented programming and has many application scenarios in hospital management systems.

4.1 Basic concepts of inheritance

  1. The nature of inheritance:

    • code reuse
    • Establish parent-child relationships between classes
    • Achieve polymorphism
  2. Characteristics of inheritance:

    • Single rootness: A class can only have one direct parent
    • Transitive: Subclasses inherit all characteristics of the parent class, including characteristics inherited by the parent class from its parent class
    • Subclasses can extend the functionality of the parent class
    • Subclasses can override methods of parent classes

4.2 Example of hospital employee inheritance system

// 基类:医院员工
public abstract class HospitalEmployee
{
    protected string id;
    protected string name;
    public string Department { get; set; }
    public DateTime HireDate { get; set; }

    // 构造函数
    public HospitalEmployee(string id, string name)
    {
        this.id = id;
        this.name = name;
    }

    // 虚方法 - 允许子类重写
    public virtual string GetDutyDescription()
    {
        return $"{name}在{Department}工作";
    }

    // 抽象方法 - 子类必须实现
    public abstract decimal CalculateSalary();
}

// 护士类
public class Nurse : HospitalEmployee
{
    public string NursingLevel { get; set; }
    public string Shift { get; set; }
    private decimal baseSalary;

    public Nurse(string id, string name, string level)
        : base(id, name)
    {
        NursingLevel = level;
        SetBaseSalary();
    }

    private void SetBaseSalary()
    {
        switch (NursingLevel)
        {
            case "初级": baseSalary = 5000M; break;
            case "中级": baseSalary = 7000M; break;
            case "高级": baseSalary = 9000M; break;
            default: baseSalary = 4000M; break;
        }
    }

    public override string GetDutyDescription()
    {
        return $"{name}是{Department}的{NursingLevel}级护士,{Shift}班次";
    }

    public override decimal CalculateSalary()
    {
        decimal shiftBonus = Shift == "夜班" ? 1000M : 0M;
        return baseSalary + shiftBonus;
    }
}

// 主管护士类
public class HeadNurse : Nurse
{
    public List<Nurse> TeamMembers { get; set; }
    private const decimal MANAGEMENT_BONUS = 2000M;

    public HeadNurse(string id, string name)
        : base(id, name, "主管")
    {
        TeamMembers = new List<Nurse>();
    }

    public void AddTeamMember(Nurse nurse)
    {
        TeamMembers.Add(nurse);
    }

    public override decimal CalculateSalary()
    {
        return base.CalculateSalary() + MANAGEMENT_BONUS;
    }

    // 新增的管理方法
    public string GenerateTeamReport()
    {
        StringBuilder report = new StringBuilder();
        report.AppendLine($"{Department}护理团队报告");
        report.AppendLine($"主管护士:{name}");
        report.AppendLine($"团队成员:{TeamMembers.Count}人");
        foreach (var nurse in TeamMembers)
        {
            report.AppendLine($"- {nurse.GetDutyDescription()}");
        }
        return report.ToString();
    }
}

5. set

In hospital information systems, we often need to process a collection of multiple data items, such as patient lists, drug inventories, etc. C#provides multiple collection types for us to use.

5.1 Detailed explanation of ArrayList

ArrayList is a non-generic collection that can store objects of any type.

Features:

  1. Dynamic size: Automatically expand capacity
  2. Different types of data can be stored
  3. Type conversion required, poor performance
  4. Not recommended in new code, generic List is recommended
public class PatientListManager
{
    private ArrayList patientList = new ArrayList();

    public void DemonstrateArrayList()
    {
        // 添加不同类型的数据
        patientList.Add("张三");           // 字符串
        patientList.Add(new Patient());    // 患者对象
        patientList.Add(42);               // 数字

        // 容量和数量
        Console.WriteLine($"容量: {patientList.Capacity}"); // 默认4,按需翻倍增长
        Console.WriteLine($"实际数量: {patientList.Count}");

        // 插入元素
        patientList.Insert(0, "急诊病人");

        // 检查包含
        bool hasPatient = patientList.Contains("张三");

        // 遍历(需要类型转换)
        foreach (object item in patientList)
        {
            if (item is Patient patient)
            {
                Console.WriteLine($"病人: {patient.Name}");
            }
        }

        // 删除操作
        patientList.Remove("张三");        // 删除特定元素
        patientList.RemoveAt(0);          // 删除指定位置的元素
        patientList.Clear();              // 清空集合
    }
}

5.2 Comparison between Hashtable and Dictionary

Key-value pair sets are commonly used in medical systems, such as drug inventory management.

Hashtable (non-generic):

  • Both keys and values are of type object
  • Type conversion required
  • poor performance
  • Not recommended in new code

Dictionary<TKey, TValue>(generic):

  • type-safe
  • better performance
  • recommended
public class MedicineInventoryManager
{
    // Hashtable示例(旧方式)
    private Hashtable medicineStockOld = new Hashtable();

    // Dictionary示例(推荐方式)
    private Dictionary<string, int> medicineStock = new Dictionary<string, int>();

    public void CompareCollections()
    {
        // Hashtable操作
        medicineStockOld.Add("阿莫西林", 100);
        medicineStockOld["布洛芬"] = 50;

        // 类型转换问题示例
        int oldStock = (int)medicineStockOld["阿莫西林"]; // 需要显式转换

        // Dictionary操作
        medicineStock.Add("阿莫西林", 100);
        medicineStock["布洛芬"] = 50;

        // 安全的值获取
        if (medicineStock.TryGetValue("阿莫西林", out int stock))
        {
            Console.WriteLine($"阿莫西林库存: {stock}");
        }

        // 检查键是否存在
        if (medicineStock.ContainsKey("布洛芬"))
        {
            medicineStock["布洛芬"] -= 10; // 减少库存
        }

        // 遍历比较
        foreach (DictionaryEntry entry in medicineStockOld)
        {
            Console.WriteLine($"药品: {entry.Key}, 库存: {entry.Value}");
        }

        foreach (KeyValuePair<string, int> kvp in medicineStock)
        {
            Console.WriteLine($"药品: {kvp.Key}, 库存: {kvp.Value}");
        }

        // 仅遍历键或值
        foreach (string medicine in medicineStock.Keys)
        {
            Console.WriteLine($"药品: {medicine}");
        }

        // 转换为列表
        List<string> medicineList = medicineStock.Keys.ToList();
    }
}

5.3 List detailed explanation

List is the most commonly used generic collection type, providing type safety and better performance.

public class NursingScheduleManager
{
    private List<Nurse> nurses = new List<Nurse>();

    public void DemonstrateList()
    {
        // 添加元素
        nurses.Add(new Nurse("N001", "张护士", "初级"));
        nurses.Add(new Nurse("N002", "李护士", "中级"));

        // 批量添加
        var newNurses = new List<Nurse>
        {
            new Nurse("N003", "王护士", "高级"),
            new Nurse("N004", "赵护士", "中级")
        };
        nurses.AddRange(newNurses);

        // 查找操作
        Nurse foundNurse = nurses.Find(n => n.NursingLevel == "中级");
        List<Nurse> juniorNurses = nurses.FindAll(n => n.NursingLevel == "初级");

        // 排序
        nurses.Sort((n1, n2) => n1.NursingLevel.CompareTo(n2.NursingLevel));

        // LINQ操作
        var dayShiftNurses = nurses.Where(n => n.Shift == "白班").ToList();
        var nurseCount = nurses.Count(n => n.NursingLevel == "中级");
        var orderedNurses = nurses.OrderBy(n => n.Name).ToList();

        // 转换
        var nurseNames = nurses.Select(n => n.Name).ToList();

        // 检查条件
        bool hasNightNurse = nurses.Any(n => n.Shift == "夜班");
        bool allJunior = nurses.All(n => n.NursingLevel == "初级");

        // 删除操作
        nurses.Remove(foundNurse);
        nurses.RemoveAll(n => n.NursingLevel == "实习");

        // 范围操作
        var someNurses = nurses.GetRange(0, 2); // 获取前两个护士
        nurses.RemoveRange(0, 2);              // 删除前两个护士
    }
}

6. Detailed explanation of type conversion

In hospital information systems, type conversions are often used to process different types of medical staff and medical records.

6.1 Basic concepts of type conversion

  1. Implicit conversion: Automatic, safe and without data loss
  2. Explicit conversion: It needs to be done manually and may pose a risk of data loss
  3. Reference type conversions: type conversions involving inheritance relationships

6.2 Examples of type conversion in medical systems

public class StaffManager
{
    public void DemonstrateTypeConversion()
    {
        // 基本类型转换
        int heartRate = 75;
        double hrDouble = heartRate;    // 隐式转换
        decimal hrDecimal = (decimal)hrDouble; // 显式转换

        // 字符串转换
        string hrString = heartRate.ToString();
        int parsedHR = int.Parse("75"); // 字符串转数字

        // TryParse安全转换
        if (int.TryParse("75", out int result))
        {
            Console.WriteLine($"转换成功:{result}");
        }

        // 引用类型转换示例
        HospitalEmployee employee = new Nurse("N001", "张护士", "初级");

        // 1. is运算符 - 检查类型
        if (employee is Nurse)
        {
            Console.WriteLine("这是一名护士");
        }
        else if (employee is Doctor)
        {
            Console.WriteLine("这是一名医生");
        }

        // 2. as运算符 - 安全转换
        Nurse nurse = employee as Nurse;
        if (nurse != null)
        {
            Console.WriteLine($"护士级别: {nurse.NursingLevel}");
        }

        // 3. 显式转换
        try
        {
            Nurse nurse2 = (Nurse)employee;
            Console.WriteLine($"转换成功: {nurse2.NursingLevel}");
        }
        catch (InvalidCastException ex)
        {
            Console.WriteLine($"转换失败: {ex.Message}");
        }

        // 4. 模式匹配(C# 7.0+)
        if (employee is Nurse nurseMatch)
        {
            Console.WriteLine($"匹配成功: {nurseMatch.NursingLevel}");
        }

        // 5. switch模式匹配
        string GetEmployeeInfo(HospitalEmployee emp)
        {
            return emp switch
            {
                Nurse n => $"护士 {n.Name}, 级别 {n.NursingLevel}",
                Doctor d => $"医生 {d.Name}, 专业 {d.Specialty}",
                _ => $"员工 {emp.Name}"
            };
        }
    }

    // 自定义转换示例
    public class VitalSignsConverter
    {
        public static implicit operator string(VitalSigns vs)
        {
            return $"体温: {vs.Temperature}℃, 心率: {vs.HeartRate}次/分";
        }

        public static explicit operator VitalSigns(string data)
        {
            // 简单示例,实际应该有更复杂的解析逻辑
            var parts = data.Split(',');
            return new VitalSigns
            {
                Temperature = decimal.Parse(parts[0]),
                HeartRate = int.Parse(parts[1])
            };
        }
    }
}

6.3 Type conversion best practices

  1. Priority use of safe conversion methods:

    • Use TryParse instead of Parse
    • Use the as operator instead of direct type conversion
    • Always check conversion results
  2. Handle conversion exceptions:

public decimal ParseTemperature(string temp) { try { return decimal.Parse(temp); } catch (FormatException) { Console.WriteLine("温度格式不正确"); return 0; } catch (OverflowException) { Console.WriteLine("温度值超出范围"); return 0; } }


## summary

In this article, we discuss in detail several important concepts in C#through the actual scenario of hospital information systems:

1. ** Namespace **

- Understand the organizational structure of namespaces
- Master multiple ways to use namespaces
- Learned project reference and namespace import

2. ** Value types and reference types **

- Understand the essential differences between the two types
- Master different ways of memory storage
- Learned to understand type characteristics through medical data

3. ** String processing **

- Master common string operation methods
- Learned to process medical record texts
- Understand the special nature of strings

4. ** Inheritance **

- Understanding the concept of inheritance through the hospital employee system
- Master the characteristics and usage of inheritance
- Learned method rewriting and constructor calls

5. ** Gathering *

- Understand the characteristics of different collection types
- Master the common operations of collection
- Learned to choose the right collection type

6. ** Type conversion **
- Master various types of conversion methods
- Learned safe type conversion practices
- Understand the application of type conversion in medical systems

These concepts will help us build more complex medical information system functions.
Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/22/2026

Support for. NET by operating system versions (250707 update)

Use virtual machines and test machines to test the support of each version of the operating system for. NET. After installing the operating system, it is passed by measuring the corresponding running time of the installation and being able to run the Stardust Agent.

继续阅读
同分类 / 同标签 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.

继续阅读