C# 扩展方法

扩展方法能够向现有类型添加方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是LINQ的基础,许多LINQ方法(如Where、Select等)都是通过扩展方法实现的。

步骤

1、创建一个静态类

2、将静态方法定义为扩展方法,其中扩展方法的第一个参数指定了适用扩展方法的类型。在第一个参数之前加上this 修饰符。

实例一:

cs 复制代码
public static class MyExtensions
{
    public static void SayHello(this string str)
    {
        Console.WriteLine("Hello World!");
    }
}

string human = "abc";
human.SayHello();

实例二

cs 复制代码
// 定义扩展方法
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
    
    public static string Reverse(this string input)
    {
        char[] chars = input.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
}

// 使用扩展方法
string text = "Hello";
bool empty = text.IsNullOrEmpty(); // 调用扩展方法
string reversed = text.Reverse();  // 调用另一个扩展方法

特点

  1. 静态类中定义:扩展方法必须在静态类中定义

  2. this关键字 :第一个参数前使用this关键字

  3. 命名空间:使用时需要引入包含扩展方法的命名空间

  4. 优先级:如果类型本身有同名方法,实例方法优先级高于扩展方法

注意事项

  1. 扩展方法不能访问私有或受保护成员

  2. 过度使用可能导致代码难以理解和维护

  3. 与实例方法同名时,实例方法优先

  4. 不支持扩展属性、事件等,只能扩展方法

相关推荐
公子小六6 分钟前
推荐一种手动设置异步线程等待机制的解决方案
windows·microsoft·c#·.net
code bean36 分钟前
【C++】全局函数和全局变量
开发语言·c++·c#
yi碗汤园44 分钟前
C#实现对UI元素的拖拽
开发语言·ui·unity·c#
m***92381 小时前
【MySQL】C# 连接MySQL
数据库·mysql·c#
ironinfo3 小时前
C#性能优化随记
开发语言·性能优化·c#
czhc11400756635 小时前
Winform121 prograssbar Imagelist panel
c#
我是苏苏6 小时前
C#基础:如何创建一个类库并且封装成DLL
开发语言·c#
Yuyang_Leo6 小时前
eventTime+watermarker+allowedLateness到底窗口关闭时间是什么?
c#·linq
Tatalaluola6 小时前
Unity使用EPPlus读取写入表格
unity·c#·游戏引擎·excel