C#之扩展方法🔥
CZerocheng 1/27/2024 CSharp
在 C# 中,扩展方法(Extension Methods)是允许你向现有类型添加新方法的一种特殊静态方法,而无需修改原始类型的定义。扩展方法的主要目的之一是增强代码的可读性和可维护性,同时避免创建子类或使用辅助方法。
# 使用
1、定义静态方法:扩展方法必须定义在静态类中。
2、第一个参数使用 this 关键字:扩展方法的第一个参数指定被扩展的类型,并使用 this 关键字来指示它是一个扩展方法。
3、使用扩展方法:一旦定义了扩展方法,可以像调用类的实例方法一样调用它。
# 示例
下面是一个完整的例子,展示如何使用扩展方法来扩展一个对象的方法。这次我们会定义一个用于表示点(Point)的类,然后通过扩展方法为它添加一些额外的功能。
首先,我们定义一个表示二维点的 Point 类:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public void Display()
{
Console.WriteLine($"Point({X}, {Y})");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
接下来,我们定义一个静态类,并在其中编写扩展方法。这里,我们为 Point 类添加一个方法来计算距离和一个方法来平移点的位置。
public static class PointExtensions
{
// 计算两点之间的距离
public static double DistanceTo(this Point p1, Point p2)
{
int dx = p1.X - p2.X;
int dy = p1.Y - p2.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
// 平移点的位置
public static void Translate(this Point p, int dx, int dy)
{
p.X += dx;
p.Y += dy;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
现在我们可以使用这些扩展方法,就像它们是 Point 类的实例方法一样:
class Program
{
static void Main()
{
Point p1 = new Point(3, 4);
Point p2 = new Point(0, 0);
// 使用扩展方法计算距离
double distance = p1.DistanceTo(p2);
Console.WriteLine($"Distance between p1 and p2: {distance}"); // 输出 5
// 使用扩展方法平移点的位置
p1.Translate(2, 3);
p1.Display(); // 输出 Point(5, 7)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上述代码将输出:
Distance between p1 and p2: 5
Point(5, 7)
1
2
2
这个例子展示了如何定义和使用扩展方法来增强现有类的功能。通过扩展方法,可以在不修改原有类定义的情况下,添加新功能,使代码更具可读性和可维护性。