面向对象高级特性 #

一、静态类 #

1.1 静态类特点 #

  • 不能实例化
  • 不能被继承
  • 只能包含静态成员
  • 不能有构造方法

1.2 定义静态类 #

csharp
public static class MathHelper
{
    public const double PI = 3.14159265359;
    
    public static double Square(double x) => x * x;
    
    public static double Cube(double x) => x * x * x;
    
    public static double Distance(double x1, double y1, double x2, double y2)
    {
        return Math.Sqrt(Square(x2 - x1) + Square(y2 - y1));
    }
}

double area = MathHelper.PI * 5 * 5;
double dist = MathHelper.Distance(0, 0, 3, 4);

1.3 使用场景 #

csharp
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }
    
    public static string Reverse(this string value)
    {
        if (value == null) return null;
        var chars = value.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

public static class Configuration
{
    public static string ConnectionString { get; set; }
    public static int Timeout { get; set; } = 30;
    
    public static void Initialize(string connectionString, int timeout = 30)
    {
        ConnectionString = connectionString;
        Timeout = timeout;
    }
}

二、密封类 #

2.1 密封类特点 #

  • 不能被继承
  • 可以实例化
  • 可以有虚方法

2.2 定义密封类 #

csharp
public sealed class Singleton
{
    private static Singleton _instance;
    private static readonly object _lock = new();
    
    private Singleton() { }
    
    public static Singleton Instance
    {
        get
        {
            lock (_lock)
            {
                return _instance ??= new Singleton();
            }
        }
    }
    
    public void DoSomething()
    {
        Console.WriteLine("执行操作");
    }
}

2.3 密封方法 #

csharp
public class BaseClass
{
    public virtual void Method1() { }
    public virtual void Method2() { }
}

public class DerivedClass : BaseClass
{
    public sealed override void Method1()
    {
        Console.WriteLine("方法1已密封");
    }
    
    public override void Method2()
    {
        Console.WriteLine("方法2可被重写");
    }
}

2.4 使用场景 #

csharp
public sealed class ApiClient
{
    private readonly HttpClient _httpClient;
    
    public ApiClient(string baseUrl)
    {
        _httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) };
    }
    
    public async Task<string> GetAsync(string endpoint)
    {
        return await _httpClient.GetStringAsync(endpoint);
    }
    
    public async Task PostAsync<T>(string endpoint, T data)
    {
        var json = JsonSerializer.Serialize(data);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        await _httpClient.PostAsync(endpoint, content);
    }
}

三、部分类 #

3.1 部分类特点 #

  • 一个类可以分散在多个文件
  • 编译时合并
  • 所有部分必须使用partial关键字

3.2 定义部分类 #

Person.cs

csharp
public partial class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public void Introduce()
    {
        Console.WriteLine($"我是{Name},今年{Age}岁");
    }
}

Person.Business.cs

csharp
public partial class Person
{
    public string Email { get; set; }
    public string Phone { get; set; }
    
    public void Contact()
    {
        Console.WriteLine($"邮箱:{Email},电话:{Phone}");
    }
}

3.3 部分方法 #

csharp
public partial class Order
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    
    partial void OnOrderCreated();
    
    public void Create()
    {
        Console.WriteLine("创建订单");
        OnOrderCreated();
    }
}

public partial class Order
{
    partial void OnOrderCreated()
    {
        Console.WriteLine($"订单{Id}已创建,金额:{Amount}");
    }
}

3.4 自动生成代码 #

csharp
public partial class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public partial class User
{
    public void Save()
    {
        Console.WriteLine($"保存用户:{Name}");
    }
    
    public static User GetById(int id)
    {
        return new User { Id = id, Name = "用户" + id };
    }
}

四、记录类型(Record) #

4.1 记录类型特点 #

  • 不可变引用类型
  • 值相等性比较
  • 支持with表达式
  • 简洁的语法

4.2 定义记录 #

csharp
public record Person(string Name, int Age);

var person = new Person("张三", 25);
Console.WriteLine(person);

var person2 = person with { Age = 26 };
Console.WriteLine(person2);

var person3 = new Person("张三", 25);
Console.WriteLine(person == person3);

4.3 记录体 #

csharp
public record Student(string Name, int Age) : Person(Name, Age)
{
    public string StudentId { get; init; } = Guid.NewGuid().ToString();
    
    public void Study()
    {
        Console.WriteLine($"{Name}正在学习");
    }
}

4.4 可变记录 #

csharp
public record MutablePerson
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public record struct Point(int X, int Y);

4.5 记录与继承 #

csharp
public record Animal(string Name);

public record Dog(string Name, string Breed) : Animal(Name);

public record Cat(string Name, string Color) : Animal(Name);

Animal animal = new Dog("旺财", "金毛");
Console.WriteLine(animal);

五、结构体 #

5.1 结构体特点 #

  • 值类型
  • 存储在栈上
  • 不能继承
  • 可以实现接口

5.2 定义结构体 #

csharp
public struct Point
{
    public double X { get; }
    public double Y { get; }
    
    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }
    
    public double DistanceTo(Point other)
    {
        return Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
    }
    
    public override string ToString() => $"({X}, {Y})";
}

var p1 = new Point(0, 0);
var p2 = new Point(3, 4);
Console.WriteLine(p1.DistanceTo(p2));

5.3 readonly结构体 #

csharp
public readonly struct Rectangle
{
    public double Width { get; }
    public double Height { get; }
    
    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }
    
    public double Area => Width * Height;
    public double Perimeter => 2 * (Width + Height);
}

5.4 ref结构体 #

csharp
public ref struct SpanWrapper
{
    public Span<int> Data { get; }
    
    public SpanWrapper(Span<int> data)
    {
        Data = data;
    }
    
    public void Process()
    {
        for (int i = 0; i < Data.Length; i++)
        {
            Data[i] *= 2;
        }
    }
}

六、枚举 #

6.1 定义枚举 #

csharp
public enum DayOfWeek
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

public enum HttpStatus
{
    OK = 200,
    Created = 201,
    BadRequest = 400,
    Unauthorized = 401,
    NotFound = 404,
    InternalServerError = 500
}

6.2 标志枚举 #

csharp
[Flags]
public enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4,
    Delete = 8,
    All = Read | Write | Execute | Delete
}

var perm = Permissions.Read | Permissions.Write;
Console.WriteLine(perm.HasFlag(Permissions.Read));
Console.WriteLine((perm & Permissions.Write) == Permissions.Write);

6.3 枚举方法 #

csharp
public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        var field = value.GetType().GetField(value.ToString());
        var attr = field?.GetCustomAttribute<DescriptionAttribute>();
        return attr?.Description ?? value.ToString();
    }
}

public enum Status
{
    [Description("待处理")]
    Pending,
    [Description("处理中")]
    Processing,
    [Description("已完成")]
    Completed
}

七、总结 #

高级特性要点:

特性 说明
静态类 工具类、常量
密封类 防止继承
部分类 代码分离
记录 不可变数据
结构体 值类型

下一步,让我们学习集合框架!

最后更新:2026-03-26