一篇文章搞懂扩展方法(一篇文章搞懂扩展方法怎么写)

一篇文章搞懂扩展方法(一篇文章搞懂扩展方法怎么写)

编码文章call10242025-02-01 4:12:1910A+A-

扩展方法是C#中的一种特性,允许你向现有类型添加新方法,而无需修改原有类型。它们让代码更简洁、更易读。简单来说,就是你可以给已有的类型“贴上”新功能,而不需要去动原来的代码。

1.1.1. 什么是扩展方法?

扩展方法是定义在静态类中的静态方法,但可以像实例方法一样调用。第一个参数使用 this 关键字,表示要扩展的类型。扩展方法既可以是无参的,也可以是有参的;

注意:扩展方法的本质是静态方法,因此可以通过类来调用,同时实例也可以调用扩展方法:

public static class StringExtensions
{
 ? ?public static bool IsNullOrEmpty(this string value)
 ?  {
 ? ? ? ?return string.IsNullOrEmpty(value);
 ?  }
}

// 通过实例调用扩展方法
string myString = "Hello";
bool result1 = myString.IsNullOrEmpty();

// 通过类名调用扩展方法
bool result2 = StringExtensions.IsNullOrEmpty(myString);

1.1.2. 基本语法

public static class 扩展方法类
{
 ? ?public static 返回类型 扩展方法名(this 扩展类型 参数列表)
 ?  {
 ? ? ? ?// 方法逻辑
 ?  }
}

1.1.3. 扩展方法的常见示例

(1) 统计字符串单词数量

public static class StringExtensions
{
 ? ?public static int WordCount(this string str)
 ?  {
 ? ? ? ?if (string.IsNullOrWhiteSpace(str))
 ? ? ? ? ? ?return 0;

 ? ? ? ?string[] words = str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
 ? ? ? ?return words.Length;
 ?  }
}

public class Program
{
 ? ?public static void Main()
 ?  {
 ? ? ? ?string text = "Hello World from C#";
 ? ? ? ?int wordCount = text.WordCount();//我们可以像调用 `string` 类型的方法一样使用 `WordCount`:
 ? ? ? ?Console.WriteLine($"Word Count: {wordCount}"); ?// 输出: Word Count: 4
 ?  }
}

(2) 判断整数是否为偶数:

int number = 4;
bool isEven = number.IsEven();
Console.WriteLine($"{number} is even: {isEven}"); ?// 输出: 4 is even: True

public static class IntExtensions
{
 ? ?public static bool IsEven(this int number)
 ?  {
 ? ? ? ?return number % 2 == 0;
 ?  }
}

(3) 判断日期是否为周末:

DateTime today = DateTime.Now;
bool isWeekend = today.IsWeekend();//调用扩展方法IsWeekend()
Console.WriteLine($"{today.ToShortDateString()} is weekend: {isWeekend}");

public static class DateTimeExtensions
{
 ? ?public static bool IsWeekend(this DateTime date)
 ?  {
 ? ? ? ?return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
 ?  }
}

(4) 查找大于给定值的所有元素:

public class Program
{
 ? ?public static void Main()
 ?  {
 ? ? ? ?List numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 ? ? ? ?List greaterThanFive = numbers.FindGreaterThan(5);//调用扩展方法FindGreaterThan
 ? ? ? ?Console.WriteLine(string.Join(", ", greaterThanFive)); ?// 输出: 6, 7, 8, 9, 10
 ?  }
}

public static class ListExtensions
{
 ? ?public static List FindGreaterThan(this List list, int value)
 ?  {
 ? ? ? ?return list.Where(x => x > value).ToList();
 ?  }
}
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4