2023-03-28
编程语言
00

目录

1. 什么是拓展方法?
2. 拓展方法的作用
3. 拓展方法的基本语法
3.1 定义拓展方法的规则
3.2 示例:为 string 类型添加 ToInt 方法
4. 调用规则
5. 常见应用场景
5.1 拓展 List<T> 类型的方法(洗牌算法)
5.2 拓展 DateTime 类型的方法(计算年龄)
5.3 拓展 Enum 类型的方法(获取描述)

1. 什么是拓展方法?

拓展方法(Extension Methods)是 C# 3.0 引入的一种特性,允许 在不修改原有类型代码的情况下,为现有类型(包括类、结构体、接口等)添加新的方法

2. 拓展方法的作用

  • 对现有类型添加新方法,无需修改该类型的源代码。
  • 适用于第三方库或 sealed(无法继承的类)。
  • 使代码更简洁,避免使用静态工具类。
  • 支持链式调用,提高代码可读性。

3. 拓展方法的基本语法

3.1 定义拓展方法的规则

  1. 必须是静态方法
  2. 必须定义在静态类中
  3. 第一个参数必须使用 this 关键字,指定要拓展的类型
  4. 调用时不需要传入 this 参数

3.2 示例:为 string 类型添加 ToInt 方法

csharp
using System; public static class StringExtensions { public static int ToInt(this string str) { int result; return int.TryParse(str, out result) ? result : 0; } } class Program { static void Main() { string number = "123"; int intValue = number.ToInt(); Console.WriteLine(intValue); // 输出:123 } }

4. 调用规则

  • 可以像实例方法一样调用
    csharp
    string text = "100"; int value = text.ToInt();
  • 也可以直接调用静态方法
    csharp
    int value = StringExtensions.ToInt("100");
  • 扩展方法不会覆盖实例方法,如果类型本身已经定义了相同名称的方法,则 实例方法优先

5. 常见应用场景

5.1 拓展 List<T> 类型的方法(洗牌算法)

csharp
using System; using System.Collections.Generic; public static class ListExtensions { private static Random random = new Random(); public static void Shuffle<T>(this List<T> list) { int n = list.Count; for (int i = 0; i < n; i++) { int j = random.Next(i, n); (list[i], list[j]) = (list[j], list[i]); } } }

5.2 拓展 DateTime 类型的方法(计算年龄)

csharp
using System; public static class DateTimeExtensions { public static int GetAge(this DateTime birthDate) { var today = DateTime.Today; int age = today.Year - birthDate.Year; if (birthDate > today.AddYears(-age)) age--; return age; } }

5.3 拓展 Enum 类型的方法(获取描述)

csharp
using System; using System.ComponentModel; public static class EnumExtensions { public static string GetDescription(this Enum value) { var field = value.GetType().GetField(value.ToString()); var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)); return attribute?.Description ?? value.ToString(); } }

本文作者:xuxuxuJS

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!