面向对象

C# 教程 · 第 4 章 · 6 次浏览

C# 是彻底面向对象的语言。类和 C++/Java 类似,但有几个自己的特性:属性(Property)、自动属性、表达式体方法。

属性 Property

属性是 C# 的特色:get/set 访问器封装字段,外部像访问字段一样用。自动属性 { get; set; } 编译器自动生成存储字段。

封装

public/private/protected 访问修饰符;readonly 只读字段。

构造与初始化

构造函数初始化对象;对象初始化器:new Student { Name = "张三" }。

代码示例

using System;

public class Student {
    // 自动属性
    public string Name { get; set; }
    public int Age { get; private set; }    // 外部只读

    // 构造
    public Student(string name, int age) {
        Name = name;
        Age = age;
    }

    public string Intro() => $"我是{Name},{Age}岁";  // 表达式体

    public void Birthday() => Age++;
}

class Program {
    static void Main() {
        var s = new Student("张三", 20);
        Console.WriteLine(s.Intro());
        s.Birthday();
        Console.WriteLine($"过生日后: {s.Age}岁");
    }
}