Menu
CoddyTech

扩展方法

本课属于 Coddy C# 学习旅程的“面向对象编程”单元。第 39 课,共 70 课。

扩展方法可以让你在不修改现有类型的源代码或创建派生类的情况下,为这些类型添加新方法。它们看起来就像是类型的原生方法,让你的代码更易读、更直观。

要创建扩展方法,请在静态类中定义一个静态方法,并在第一个参数前加上 this 关键字:

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(' ').Length;
    }
}

现在你可以直接对任何字符串调用这个方法:

string sentence = "Hello World Today";
int count = sentence.WordCount();  // 3

this string str 参数告诉编译器,这个方法扩展了 string 类型。当你调用 sentence.WordCount() 时,编译器会在后台将其转换为 StringExtensions.WordCount(sentence)。

扩展方法还可以接受额外的参数:

public static bool IsLongerThan(this string str, int length)
{
    return str.Length > length;
}

// 用法
bool result = "Hello".IsLongerThan(3);  // true

这种技术在 LINQ 中被广泛使用,例如 Where() 和 Select() 是 IEnumerable 的扩展方法。扩展方法功能强大,可以为你无法控制的类型添加实用函数,让代码保持简洁且富有表现力。

challenge icon

挑战

简单

让我们为整数创建一组实用的扩展方法,添加一些你期望内置支持的便捷功能。你将创建一个静态类,其中包含可直接对任意整数调用的扩展方法,让代码更具表现力,也更易读。

你将把代码分到两个文件中:

  • IntExtensions.cs:在 Utilities 命名空间中创建一个名为 IntExtensions 的静态类。这个类将包含用于增强 int 类型的扩展方法:
    • IsEven():如果数字是偶数,则返回 true;否则返回 false
    • Square():返回该数字与自身相乘的结果
    • IsInRange(int min, int max):如果数字在 min 和 max 之间(包括两者),则返回 true;否则返回 false
    请记住,扩展方法必须是静态类中的静态方法,并且第一个参数要使用 this 关键字来指定要扩展的类型。
  • Program.cs:在主文件中,从输入中读取一个整数,并演示全部三个扩展方法。像调用内置方法一样,直接在这个整数上调用每个方法,然后打印结果。

你将收到三个输入:

  • 要测试的数字(整数)
  • 范围检查的最小值(整数)
  • 范围检查的最大值(整数)

按照以下格式打印输出:

Is {number} even? {True/False}
Square of {number}: {result}
Is {number} in range [{min}-{max}]? {True/False}

例如,如果输入是 7、5 和 10,输出应为:

Is 7 even? False
Square of 7: 49
Is 7 in range [5-10]? True

注意,你可以多么自然地写出 number.IsEven() 和 number.Square()。这些扩展方法就像一直都是整数类型的一部分一样!

亲手试试

using System;
using Utilities;

class Program
{
    public static void Main(string[] args)
    {
        // 读取输入
        int number = Convert.ToInt32(Console.ReadLine());
        int min = Convert.ToInt32(Console.ReadLine());
        int max = Convert.ToInt32(Console.ReadLine());

        // TODO: 使用 'number' 的扩展方法并打印结果
        // 调用 number.IsEven()、number.Square() 和 number.IsInRange(min, max)
        // 按以下格式打印:
        // {number} 是偶数吗?{True/False}
        // {number} 的平方:{result}
        // {number} 在范围 [{min}-{max}] 内吗?{True/False}

    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: C# 在线编译器